Set background of a selected listview row

2019-08-23 06:40发布

I have a listview which is populated with locations, When you click on a location this brings up jobs to be done within this location. When all jobs have been completed you then click on a ok button now at this point I want the selected location row in the listview background colour to change. What I have so far for the button

 mOkBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            View listView = getActivity().findViewById(R.id.area_list);  
            listView.setBackgroundColor(Color.GREEN);
            mArea.checkResult = CheckResult.OK;
            mArea.checkTimeStamp = System.currentTimeMillis()/1000L;
            showResults();
        }
    });

At the moment this changes the whole listview green, but im not sure how to get it to change just the selected row.

thx

2条回答
趁早两清
2楼-- · 2019-08-23 06:57

For setting the colour, you need a selector. You can set this on your list using the android:listSelector attribute as :

 <ListView 
 android:id="@+id/foodlistview"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:cacheColorHint="#00000000"
 android:scrollbarFadeDuration="0"
 android:divider="@android:color/white"
 android:dividerHeight="2px"
 android:listSelector="list_selector"
 ></ListView>

And list_selector.xml :

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_enabled="false" android:state_focused="true"
        android:drawable="@drawable/item_disabled" />
  <item android:state_pressed="true"
        android:drawable="@drawable/item_pressed" />
  <item android:state_focused="true"
        android:drawable="@drawable/item_focused" />
</selector>
查看更多
Explosion°爆炸
3楼-- · 2019-08-23 07:18

You can set the background color of listview as follows,

 ListView listview=new ListView(this);
 listview.setBackgroundColor(Color.WHITE);

If your listview shows black when you scrolling the listview then add the some code in xml as

android:cacheColorHint="#00000000"
 android:scrollbarFadeDuration="0"

I think it may helpful to you.

<RelativeLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:background="@drawable/plainbg">


 <ListView 
 android:id="@+id/foodlistview"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:cacheColorHint="#00000000"
 android:scrollbarFadeDuration="0"
 android:divider="@android:color/white"
 android:dividerHeight="2px"
 ></ListView></RelativeLayout>
查看更多
登录 后发表回答