vendredi 22 mai 2015

Listview - setting initial/default row - with custom background

How can I initially set a default list row to e.g. 3 with the row clearly having a visual effect? The list is populated with (rounded) list items.

I see many developers struggling, so I hope we can come with a simple solution. I prepared an example that high lights the row upon a click. This works great!

First I show you the code with custom list item layouts. Then I show what I tried for setting the initial row to e.g. 3.

List<String> items = Arrays.asList( "First", "Two", "Three", "Four"); 
ArrayAdapter<String> adapter = new ArrayAdapter<String>( this, R.layout.string_entry, items);
ListView listview = (ListView) findViewById( R.id.the_list);
listview.setAdapter( adapter);
adapter.notifyDataSetChanged();
listview.invalidate();
listview.setOnItemClickListener( new OnItemClickListener() {
    @Override
    public void onItemClick( AdapterView<?> parent, View view, int position, long id) {
        view.setSelected(true);
        Log.v( "List1", "Clicked");
    }
    });

The listview layout is:

<ListView
    android:id="@+id/the_list"
    android:layout_width="match_parent"
    android:layout_height="150dp"
    android:choiceMode="singleChoice"
    android:scrollbars="vertical" />

The list item layout is:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://ift.tt/nIICcg"
    android:id="@android:id/text1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/bg_key_nice"
    android:text="demo text" />

The selector bg_key_nice is:

<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://ift.tt/nIICcg">
    <item 
        android:state_selected="true"
        android:drawable="@drawable/customshape_pressed"/>
    <item
        android:drawable="@drawable/customshape" />
</selector>

I will show only customshape(.xml), the pressed version has only a different colour:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://ift.tt/nIICcg" 
    android:shape="rectangle"> 
    <gradient  
        android:startColor="#ececc9"
        android:endColor="#d7d7b7" 
        android:angle="270"/> 
   <corners 
        android:bottomRightRadius="15dp" 
        android:bottomLeftRadius="15dp" 
        android:topLeftRadius="15dp" 
        android:topRightRadius="15dp"/> 
</shape> 

What I tried so far without any effect is:

1 - listview.setSelection( 3); --> no visual effect

2 - listview.setItemChecked( 3,true); --> no visual effect

3 - listview.setItemChecked(3, true); listview.performItemClick( listview.getSelectedView(), 3, 1); // --> will crash on getSelectedView

Aucun commentaire:

Enregistrer un commentaire