【发布时间】:2021-10-21 14:36:54
【问题描述】:
我的问题是关于 Android/Java。
我想从我的自定义视图中访问其他视图。
我的 main.xml:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/mainLinearLayout1">
<org.javaforum.input
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
required=""
android:hint="Enter your E-Mail"
oninvalid="this.setCustomValidity('SO - Please enter a correct E-Mail!!!')"/>
<org.javaforum.input
android:layout_width="wrap_content"
android:layout_height="wrap_content"
inputType="submit"/>
</LinearLayout>
所以当点击第二个“输入”视图时,我想检查第一个“输入”视图中是否存在名为“必需”的属性。
我在 input.java 中试过这个:
public class input extends TextView{
public input(Context context, AttributeSet attr) {
super(context, attr, getIdentifier(context,attr));
}
@Override
public void onFinishInflate() {
setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
LinearLayout layout = (LinearLayout)findViewById(R.id.mainLinearLayout1);
View v = null;
for(int i=0; i<layout.getChildCount(); i++) {//Error
//Code
}
}
});
}
}
但我收到以下错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.widget.LinearLayout.getChildCount()' on a null object reference
我不明白为什么它是空的。应该已经创建了吧?
那么我怎样才能在我的自定义视图中正确获取我的 main.xml 的 LinearLayout 引用?
【问题讨论】:
标签: java android android-layout android-linearlayout android-custom-view