Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

android - Force a ListView item to stay "pressed" after being clicked?

I have a ListView that opens another activity when an item row is clicked via a onItemClick listener.

I would like that row to stay in its pressed state from the time it is clicked to the time the screen switches to a new activity. I think this would be a clearer experience for the user and you see this kind of thing with most buttons that open/close dialogs or switch activities.

I tried setting view.setPressed(true) in the onItemClick() listener but it seems to get called just a moment after the press state changed back to normal because it flickers slightly.

For example:

mListView.setOnItemClickListener(new OnItemClickListener() {

   @Override
   public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
       view.setPressed(true);
       //start an activity
   }
});

That code almost works except for the flicker (User presses the list item and it turns to its pressed state, then user lets go (completing the click) and it turns back to its normal state for a split second before turning back to the pressed state from the setPressed(true) call)

Any ideas?

Thanks

Edit: I should mention that I am using an xml drawable selector to define the normal, pressed, selected, etc states for the background of the list.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I had the exact same problem to much frustration!

It is, however, easily solved by substituting state_pressed with state_selected. The pressed state will still change rapidly before onItemClick() is called, but since your theme does not depend on state_pressed the flicker won't be visible. Once in onItemClick() you set state_selected and the item will stay selected without any flicker occurring.

Here's my selector:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Selected Item -->
    <item android:state_selected="true"
        android:drawable="@color/list_pressed" />

    <!-- Default Item -->
    <item android:state_selected="false"
        android:drawable="@android:color/list_default" />
</selector>

And my onListItemClick(...):

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    v.setSelected(true);
    //TODO: add further actions here
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...