【发布时间】:2013-04-06 00:58:19
【问题描述】:
我可以通过xml通过写来改变LinearLayout的背景
android:background="@drawable/overview"
到我的线性布局。
但是我不能以编程方式做到这一点。我尝试了以下操作:
LinearLayout Horizontal_menu = new 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);
【问题讨论】:
-
您在主题中有一个答案:1. stackoverflow.com/questions/4761686/… 2. stackoverflow.com/questions/8961071/… 尝试这些可能性并检查它是否适合您。