[英]Android ListView how to change selected item background
I will ask for help for the following problem. 我将为以下问题寻求帮助。 Very strange for me :) I trying to change the background of the selected item in ListView.
对我来说很奇怪:)我试图更改ListView中所选项目的背景。 I set item selected the following way.
我按照以下方式设置选择的项目。
drawer_home.setItemChecked(0, true);
I know that I can set the other item background color. 我知道我可以设置其他项目的背景色。 I have no problem to change all background or on active item for example but not on selected.
我没有问题,例如更改所有背景或活动项目,但未更改任何问题。
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_selected="true" android:drawable="@android:color/holo_blue_light"/>
<item android:state_checked="true" android:drawable="@android:color/holo_red_dark"/>
<item android:state_pressed="true" android:drawable="@android:color/holo_green_dark"/>
<item android:drawable="@android:color/white"/>
</selector>
android:background="@android:color/white"
android:listSelector="@drawable/listview_selector"
What I tried to change is styles on theme and the result is the same. 我试图更改的是主题样式,结果是相同的。 Everything is ok except selected item :(
一切都OK,除了选中的项目
I found a solution to my problem. 我找到了解决问题的方法。 I spend an awful lot of time to solve something so simple.
我花了很多时间来解决这么简单的问题。
At first look something so simple. 起初看起来很简单。
So I will share my experience hopefully save timf another person :) You can simply use. 因此,我将分享我的经验,希望可以节省其他人:)您可以简单地使用。
drawer_home.getChildAt(0).setBackgroundColor(Color.RED);
or 要么
drawer_home.getChildAt(drawer_home.getSelectedItemPosition()).setBackgroundColor(Color.RED);
But only if the item in ListView are static. 但仅当ListView中的项目为静态时。
And before I met this decision but because dynamically change ListView items with ArrayAdapter. 在我做出这个决定之前,是因为使用ArrayAdapter动态更改ListView项。
drawer_home.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_activated_1, home_menu_title));
It gives me an error. 它给了我一个错误。 Because obviously that content still has not loaded yet.
因为显然该内容尚未加载。 Then use the following.
然后使用以下内容。
drawer_home.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft,
int oldTop, int oldRight, int oldBottom) {
// TODO Auto-generated method stub
if(menuType == MENU_TYPE_HOME && currentPosition == 0) {
drawer_home.getChildAt(0).setBackgroundColor(0xCC4d4dff);
}
}
});
I do not have much experience with Android so that probably is not the perfect solution. 我在Android方面经验不足,因此可能不是完美的解决方案。
I will glad of a better solution. 我将为更好的解决方案而高兴。
尝试添加
<item android:state_activated="true" android:drawable="@android:color/holo_blue_light"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.