Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Layout-background on click programmatically

I can change the background of a LinearLayout via xml by writing

android:background="@drawable/overview"

to my LinearLayout.

However I can't do that programmatically. I tried following:

LinearLayout horizontal_menu = new LinearLayout(this); ... horizontal_menu.setBackgroundResource(getResources().getInteger(R.drawable.overview));

and also that source of code:

horizontal_menu.setBackground(getResources().getDrawable(R.drawable.overview));

First try throws an RuntimeException at runtime, the second line seems to do nothing -> no errors, no exceptions, no changing background on clicking...

--> overview.xml

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android">   
<item android:state_focused="true" android:drawable="@color/half_transparent"/> 
<item android:state_pressed="true" android:drawable="@color/half_transparent" />
</selector>

I hope that anyone can help me!

Thanks!

Edit:

LinearLayout content = (LinearLayout)findViewById(R.id.LinearLayout); 
LinearLayout horizontal_menu = new LinearLayout(this); 
horizontal_menu.setOrientation(LinearLayout.HORIZONTAL); 
horizontal_menu.setBackgroundResource(getResources().getInteger(R.drawable.overv‌​iew)); 
content.addView(horizontal_menu);
like image 920
user1885484 Avatar asked Jun 19 '26 15:06

user1885484


1 Answers

Set an id for layout in your layout XML file:

<LinearLayout android:id="@+id/myLinearLayout" ...

and then in your Activity, get LinearLayout with findViewById() as below:

LinearLayout ll = (LinearLayout) findViewById(R.id.myLinearLayout);

And then set background for ll with setBackground methods:

ll.setBackground(...) 
ll.setBackgroundDrawable(...)
ll.setBackgroundResource(...)
like image 108
Ali Behzadian Nejad Avatar answered Jun 21 '26 06:06

Ali Behzadian Nejad