【发布时间】:2011-09-08 12:01:12
【问题描述】:
我正在尝试将列表项在被选中时的样式应用于视图(在我的情况下为 TextView)
这里应该是橙色的风格。我发现这个外观是由一个可绘制对象定义的。所以我尝试了,所以获取可绘制对象并将其应用到我的视图中
TextView tv = new TextView(this);
tv.setText("Hello, Android");
tv.setBackgroundDrawable(new ListView(this).getSelector());
setContentView(tv);
但它不起作用。 有人知道怎么做吗?
好的,我想出了如何做到这一点。我发现帽子 ListView 使用了在 android.R.drawable 中定义的 ColorStateList list_selector_background。使用 ResourceBrowser 我知道第四种颜色是选定的可绘制对象,所以我将以下内容添加到我的代码中
StateListDrawable listDrawables= (StateListDrawable)getResources().getDrawable(android.R.drawable.list_selector_background);
listDrawables.selectDrawable(3);
Drawable highlightDrawable = listDrawables.getCurrent();
现在我可以使用 higlightDrawable 设置背景。我不知道是否可以访问 xml 中的 drawable 我还没有尝试过。感谢您的帮助!
【问题讨论】: