我创建了一个扩展 LinearLayout 并包含两个 TextView 的自定义 View 。尽管我在 onFinishInflate() 中设置了 TextView ,但稍后在这些 TextView 上调用 setText() 时,我还是遇到了空指针异常。
这是自定义 View 的代码:
public class MyCustomView extends LinearLayout{
private TextView textView1;
private TextView textView2;
public MyCustomView(Context context){
super(context);
LayoutInflater layoutInflater = LayoutInflater.from(context);
layoutInflater.inflater(R.layout.my_custom_view, this);
}
public MyCustomView(Context context, AttributeSet attrs){
super(context, attrs);
}
public MyCustomView(Context context, AttributeSet attrs, int defStyle){
super(context, attrs, defStyle);
}
@Override
protected void onFinishInflate(){
super.onFinishInflate();
textView1 = (TextView)findViewById(R.id.tv1);
textView2 = (TextView)findViewById(R.id.tv2);
}
// here's where I get the null pointer for textView1
public void setTitle(String title){
textView1.setText(title);
}
}
my_custom_view.xml 如下所示:
<?xml version="1.0" encoding="utf-8">
<my_package.myapp.MyCustomView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/tv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</my_package.myapp.MyCustomView>
我后来像这样使用自定义 View :
View view = new MyCustomView(context);
((MyCustomView)view).setTitle("Title"); // null pointer exception here
return view;
有什么想法是我误解或做错了吗?我真的很感激任何帮助。
我还注意到,如果我修改第一个构造函数以获取其他对象,然后尝试使用该对象,则该实例变量也为空。例如:
public MyCustomView(Context context, SomeObject object){
this.object = object;
}
// as with the textviews, object would be null here
public int getObjectValue(){
return object.getValue();
}
谢谢!
最佳答案
好的,这里有多个问题。
1)你的xml是错误的。如果您要将其扩展到您的类中,它应该以合并开始,而不是对您的类的引用。
2) 你的 3 个构造者都需要做通货膨胀的事情。 (这就是它失败的原因——这里将调用 2 或 3 个参数的构造函数)。
3)您不想或不需要重写 onFinishInflate。将该代码放入构造函数中。通货膨胀不是异步的,所以没有理由不这样做。
关于android - 所有自定义 View 实例变量均为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31281561/