获取 ListView 可绘制对象并手动应用
我正在尝试将列表项在选择时所具有的样式应用于视图(在我的例子中是 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 中的可绘制对象,我还没有尝试过。感谢您的帮助!
i am trying to apply the style that a list item has, when it is selected, to a View (In my case a TextView)
here it would be the orange-painted style. I found that this look is defined by a Drawable Object. So i tried, so get the drawable and applied it to my view
TextView tv = new TextView(this);
tv.setText("Hello, Android");
tv.setBackgroundDrawable(new ListView(this).getSelector());
setContentView(tv);
but it doesn't work.
Does anybody have an idea how to do that?
Ok I figured out how to do that. I found out hat ListView uses the ColorStateList list_selector_background which is defined in android.R.drawable. Using ResourceBrowser I got to know that the fourth color is the selected drawable so i added the following to my code
StateListDrawable listDrawables= (StateListDrawable)getResources().getDrawable(android.R.drawable.list_selector_background);
listDrawables.selectDrawable(3);
Drawable highlightDrawable = listDrawables.getCurrent();
Now I can set my Background using higlightDrawable. I don't know if it is possible to access the drawable in xml I did not try it yet. Thanks for help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果用代码来实现的话会很痛苦。
您需要实现一个 选择器 并让 android 知道需要哪些资源当按下、启用或聚焦视图时使用。
这是关于如何实现相同目标的示例示例。
It would be a pain to do it by code.
You need to implement a selector and let android know which resource needs to be used when the view is pressed, enabled or focused.
Here is sample example on how to achieve the same.