Change Layout-background on click programmatically

2019-06-08 04:48发布

问题:

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);

回答1:

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(...)


回答2:

I had the same problem and Based on my search there is no way to change activity or main ViewGroup styles dynamically after super.onCreate .so you should either have a XML layout and set that layout before super.onCreate or you should inflate that layout like this:

root = (LinearLayout)findViewById(R.id.rootView);
getLayoutInflater().inflate(R.layout.one,root);

note that you should have a root view to parent the layout you inflate. and when you want to change that layout just do this:

buttonclick{
        root.removeAllViewsInLayout();
        v = getLayoutInflater().inflate(R.layout.two,root);
        root.addView(v,0);
}

note that you could add or remove each widget or view by viewGroup.addView also but in my opinion Inflater is much more better choice.

EDIT:

for very nice answer in this regard see @broot answer here.