我可以通过编写xml来更改LinearLayout的背景
android:background =“ @ drawable / overview”
到我的LinearLayout。
但是我不能以编程方式做到这一点。我尝试了以下操作:
LinearLayout horizontal_menu =新的LinearLayout(this);
...
horizontal_menu.setBackgroundResource(getResources()。getInteger(R.drawable.overview));
还有那个代码源:
horizontal_menu.setBackground(getResources()。getDrawable(R.drawable.overview));
第一次尝试在运行时抛出RuntimeException,第二行似乎什么都不做->没有错误,没有异常,单击时没有改变背景...
-> 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>
我希望任何人都能帮助我!
谢谢!
编辑:
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.overview));
content.addView(horizontal_menu);
最佳答案
在布局XML文件中为布局设置ID:
<LinearLayout android:id="@+id/myLinearLayout" ...
然后在您的Activity中,使用findViewById()获取LinearLayout,如下所示:
LinearLayout ll = (LinearLayout) findViewById(R.id.myLinearLayout);
然后使用setBackground方法为ll设置背景:
ll.setBackground(...)
ll.setBackgroundDrawable(...)
ll.setBackgroundResource(...)
关于android - 以编程方式单击时更改布局背景,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15989312/