Keeping an item from a selected Listview when pressed

Asked

Viewed 1,054 times

1

I’m developing a listview, and I need to leave a selected item when I click, and then take the position of that item, in order to do the inversion of two items, which is up with what is down for example, by means of a button. I’ve been researching but the solutions I found required an API greater than 11, and I’m doing it in API 8, because my program is very simple. How do I keep selected and return the position of the item selected? Thank you for your attention.

2 answers

2


First create a class derived from LinearLayout or RelativeLayout implementing the interface Checkable

Example for LinearLayout

public class CheckableLinearLayout extends LinearLayout implements Checkable{

    private boolean checked = false;
    private static final int[] CHECKED_STATE_SET = { android.R.attr.state_checked };

    public CheckableLinearLayout(Context context) {
        super(context);
    }

    public CheckableLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

      // Requer API level 11
/*    public CheckableLinearLayout(Context context, AttributeSet attrs,
                                   int defStyle) {
          super(context, attrs, defStyle);
      }*/

    @Override
    protected int[] onCreateDrawableState(int extraSpace) {
         final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
         if (isChecked())
             mergeDrawableStates(drawableState, CHECKED_STATE_SET);
         return drawableState;
    }

    @Override
    public boolean isChecked(){
        return checked;
    }

    @Override
    public void setChecked(boolean checked) {
        this.checked = checked;
        refreshDrawableState();
    }

    @Override
    public void toggle() {
        setChecked(!checked);
    }
}  

You should then use this Layout to define the Layout of the items in your list:

list_item.xml

<?xml version="1.0" encoding="utf-8"?>

<yourPackage.CheckableLinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/listItemLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/lbId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</yourPackage.CheckableLinearLayout>  

In the data associated with the list you must have a flag boolean which shall indicate whether it is selected or not.

In the Adapter check the flag and do listItemLayout.setChecked(false) or listItemLayout.setChecked(true); according to the flag.

In the onClick associated with the list you must set the flag with true.

0

  • You could bring the most relevant part to terms content in English as well?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.