Android findViewById for a parent layout -


as can see in code, have parent layout has button. want change bg. color of parent layout randomly every time button clicked. findviewbyid(r.layout.activity_main) parent layout gives null setcontentview(r.layout.activity_main) set same layout. dont want create parent layout , add layout child,then setcontentview parentlayout , ffindviewbyid child layout.

this activity class code :

    protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);         setcontentview(r.layout.activity_main);     }  public void button1click(view view)     {                edittext edittext1;         button button1;              button1 = (button) view;         button1.setbackgroundcolor(color.gray);         edittext1 = (edittext) this.findviewbyid(r.id.edittext1);         edittext1.settext("welcome !");         relativelayout rlayout = (relativelayout) this.findviewbyid(r.layout.activity_main);         rlayout.setbackgroundcolor(color.rgb((int)math.random()*10,(int)math.random()*10,(int)math.random()*10));      } 

this xml :

<relativelayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:paddingbottom="@dimen/activity_vertical_margin"     android:paddingleft="@dimen/activity_horizontal_margin"     android:paddingright="@dimen/activity_horizontal_margin"     android:paddingtop="@dimen/activity_vertical_margin"     tools:context=".mainactivity" >      <button         android:id="@+id/button1"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_alignparentbottom="true"         android:layout_centerhorizontal="true"         android:onclick="button1click"         android:text="@string/button_click" />      <edittext         android:id="@+id/edittext1"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_alignparenttop="true"         android:layout_centerhorizontal="true"         android:ems="15"         android:inputtype="text" >          <requestfocus />     </edittext>  </relativelayout> 

add id parent relative layout:

<relativelayout xmlns:android="http://schemas.android.com/apk/res/android"     android:id="@+id/activity_main"     ...      ... </relativelayout> 

then change

relativelayout rlayout = (relativelayout) this.findviewbyid(r.layout.activity_main); 

to

relativelayout rlayout = (relativelayout) this.findviewbyid(r.id.activity_main); 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -