I have a listview in that i want when my activity starts then the first item will have background and the other items don't have any background.After that if the user selects any other item then the background of that particular item will now be blue and the rest don't have any background.Please help me on this.
My layout_effect.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true">
<shape>
<solid android:color="#ffffff" />
</shape>
</item>
<item>
<shape>
<solid android:color="#00a7eb" />
</shape>
</item>
</selector>
My GetView Code where i am setting the default Background
public View getView(int position, View convertView, ViewGroup parent) {
if(position == 0){
vi.setBackgroundResource(R.drawable.selection_effect);
vi.setSelected(true);
}
}
Any my onclickListner of the listview
onewayListView .setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "Clicked", 1000).show();
}
});
My Listview xml
<ListView
android:id="@+id/lvDepartures"
android:layout_weight="1"
android:layout_marginLeft="5dp"
android:choiceMode="singleChoice"
android:layout_height="wrap_content"
android:listSelector="@drawable/selection_effect"
android:layout_width="wrap_content"/>
Please help me how could i solve this problem i am stucked in it from last 1day.
Create a selector for listview
setOnItemClickListener
write the following functionyou should check this:
For doing this what you can do is create a selector and apply it to parent view of your
row.xml
Define color in strings.xml
<color name="blue">#009FE3</color>
Create a selector
Now apply it as
android:background="@drawable/row_selector"
for parent view of your row.Set ListView as CHOICE_MODE_SINGLE in java code
listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
And finally setAdapter to your ListView.
listview.setAdapter(adapter);
For selection of default item in ListView use,
listview.setItemChecked(position, true);
I had created a demo example for the same you can download it from my github
Remove your default list-selector in your listview or set it as null:
Hope this helps.
OnListItem click pass the selected position to the adapter and set the adapter again and in adapter check if selected position then set the background otherwise does not set the background.
I'm not sure but try putting
listView.setSelection(position);
in listview'ssetOnItemClickListener