android - All custom view instance variables are null -


i created custom view extends linearlayout , contains 2 textviews. though set text views in onfinishinflate(), null pointer exceptions when call settext() on these textviews later.

here's code 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 null pointer textview1     public void settitle(string title){         textview1.settext(title);     }  } 

my_custom_view.xml looks 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 custom view so:

view view = new mycustomview(context);  ((mycustomview)view).settitle("title");   // null pointer exception here return view; 

any ideas i'm misunderstanding or doing wrong? i'd appreciate help.

i noticed if modified first constructor take other object , later try use object, instance variable null. eg:

public mycustomview(context context, someobject object){     this.object = object; }  // textviews, object null here public int getobjectvalue(){     return object.getvalue();  } 

thanks!

ok, multiple problems here.

1)your xml wrong. should start merge, not reference class, if you're inflating class.

2)all 3 of contructors need inflation stuff. (this prt of why failed- 2 or 3 param constructor called here).

3)you not want or need override onfinishinflate. put code in constructor. inflation not asynchronous, there's no reason not to.


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -