I'm having trouble highlighting the selected entry in a ListView. I've followed the procedures in http://www.michenux.net/android-listview-highlight-selected-item-387.html. I've also tried the suggestions in Android: setselector color for listview not working to no avail. I've tried working with a ListView in a DialogFragment as well as in an Activity.
What I've noticed is that (1) I can set the Selection, but I can't query the SelectedItemPosition, (2) onItemSelected never gets called, and (3) I can't get the child View.
Here's some code:
public class ChooseDirActivity extends Activity
{
private ListView listView = null;
@Override
protected void onCreate( Bundle savedInstanceState )
{
super.onCreate( savedInstanceState );
setContentView( R.layout.choose_dir_layout );
listView = (ListView)findViewById( R.id.directory_list );
StateListDrawable selector = new StateListDrawable();
selector.addState(new int[]{android.R.attr.state_selected}, new ColorDrawable( 0x808080 ));
selector.addState( new int[]{ -android.R.attr.state_selected }, new ColorDrawable( 0xFFFFFF ) );
listView.setSelector( selector );
listView.setOnItemSelectedListener( new AdapterView.OnItemSelectedListener()
{
@Override
public void onItemSelected( AdapterView<?> adapterView, View view, int i, long l )
{
Log.i( "myApp", "onItemSelected" ); // Never called
view.setBackgroundColor( 0x808080 );
}
@Override public void onNothingSelected( AdapterView<?> adapterView ) { } } ); listView.setChoiceMode( ListView.CHOICE_MODE_SINGLE ); }
@Override
protected void onResume()
{
super.onResume();
currentDirectory = Intonia.getStorageDirectory();
ArrayList<String> dirList = getDirectoryList();
int selected = 11;
listView.setAdapter( new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, dirList ) );
Log.i( "myApp", "setting selection to " + selected );
listView.setSelection( selected );
listView.setItemChecked( selected, true );
Log.i( "myApp", "selected item position is " + listView.getSelectedItemPosition() );
View childView = listView.getChildAt( selected );
if ( childView == null )
{
Log.i( "myApp", "view at " + selected + " is null" );
}
else
childView.setBackgroundColor( 0x808080 );
Object so = listView.getItemAtPosition( selected );
Log.i( "myApp", "item at " + selected + " is " + ( so == null ? "null" : so.getClass().toString() ) );
}
}
Setting the selection does move the selected item to the top of the screen, but there doesn't appear to be any way to follow up on it.
This produces the following log output
myApp: setting selection to 11
myApp: selected item position is -1
myApp: view at 11 is null
myApp: item at 11 is class java.lang.String
Can anyone help me?
Copyright Notice:Content Author:「Jerry Agin」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/30766584/cant-highlight-selected-item-in-a-listview