I created a custom view that extends LinearLayout and contains two TextViews. Even though I set the text views in onFinishInflate(), I get null pointer exceptions when I call setText() on these textviews later.
Here's the code for the custom 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 looks like this:
<?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>
I later use the custom view like so:
View view = new MyCustomView(context);
((MyCustomView)view).setTitle("Title"); // null pointer exception here
return view;
Any ideas what I'm misunderstanding or doing wrong? I'd really appreciate any help.
I also noticed that if I modified the first constructor to take some other object and then later try to use this object, that instance variable is also null. Eg:
public MyCustomView(Context context, SomeObject object){
this.object = object;
}
// as with the textviews, object would be null here
public int getObjectValue(){
return object.getValue();
}
Thanks!