Reputation: 11
As you can see in the code, I have a parent layout which has a button. I want to change the bg. color of parent layout randomly every time the button is clicked. But findViewById(R.layout.activity_main) for my parent layout gives null as setContentView(R.layout.activity_main) is set for the same layout. I dont want to create another parent layout and add this layout as its child,then setContentView for parentlayout and then ffindViewById my child layout.
this is the 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 is the 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>
Upvotes: 0
Views: 5706
Reputation: 16164
Add an id to the 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);
Upvotes: 4