本文介绍了更改单击版式,背景编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以通过编写修改通过XML一个的LinearLayout的背景

我的LinearLayout。

不过,我不能这样做编程。我尝试以下操作:

和也code的来源:

第一次尝试抛出的RuntimeException在运行时,第二行似乎做什么 - >没有错误,没有例外,在点击没有变化的背景下...

- > overview.xml

 < XML版本=1.0编码=UTF-8&GT?;
<选择的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android>
<项目安卓state_focused =真正的机器人:可绘制=@色/ half_transparent/>
<项目的android:STATE_ pressed =真正的机器人:可绘制=@色/ half_transparent/>
< /选择器>
 

我希望有人能帮助我!

谢谢!

编辑:

 的LinearLayout含量=(的LinearLayout)findViewById(R.id.LinearLayout);
的LinearLayout horizo​​ntal_menu =新的LinearLayout(本);
horizo​​ntal_menu.setOrientation(LinearLayout.HORIZONTAL);
horizo​​ntal_menu.setBackgroundResource(getResources()getInteger(R.drawable.overv IEW));
content.addView(horizo​​ntal_menu);
 

解决方案

在布局XML文件中设置ID进行布局:

 <的LinearLayout机器人:ID =@ + ID / myLinearLayout......
 

,然后在你的活动,获得的LinearLayout与findViewById()如下:

 的LinearLayout LL =(的LinearLayout)findViewById(R.id.myLinearLayout);
 

然后设置LL背景的setBackground方法:

  ll.setBackground(...)
ll.setBackgroundDrawable(...)
ll.setBackgroundResource(...)
 

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

to my LinearLayout.

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

and also that source of code:

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);
解决方案

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

这篇关于更改单击版式,背景编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 18:14