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 selec
you should check this:
public View getView(int position, View convertView, ViewGroup parent) {
if(position%2 == 0){
vi.setBackgroundResource(R.drawable.selection_effect);
vi.setSelected(true);
}else{
// set another background.
}
}
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
<item android:drawable="@color/blue" android:state_activated="true" />
<item android:drawable="@color/blue" android:state_focused="true" />
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
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's setOnItemClickListener
Create a selector for listview
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/button_pressed_yellow"
android:state_pressed="true" />
<item android:drawable="@drawable/button_focused_orange"
android:state_focused="true" />
<item android:drawable="@drawable/button_normal_green" />
</selector>
setOnItemClickListener
write the following function
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
""+position, Toast.LENGTH_SHORT).show();
}
});
Remove your default list-selector in your listview or set it as null:
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:listSelector="@null" >
</ListView>
Hope this helps.