3

I have create simple multi selection list view using array adapter. i wanna set background color particular list item. But suppose i select 2 item mean set background and also set 12th position and 22 position like wise selected automatically. please suggest me problem.

Code Black.

public class MainActivity extends Activity {

ListView lvCountry;

ArrayList<Integer> list = new ArrayList<Integer>();
String[] country = { "India", "USA", "Russsia", "China", "Pakistan",
        "Canada", "UK", "arcot", "vellore", "gudiyattam", "arani",
        "palani", "chennai", "padi", "velacherry", "ambattur",
        "ambatttur ot", "maduravoyal", "guindy" };

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    lvCountry = (ListView) findViewById(R.id.listView1);
    // Array adapter
    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
            MainActivity.this, android.R.layout.simple_list_item_1, country);
    lvCountry.setAdapter(arrayAdapter);

    // list selection part
    lvCountry.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1,
                int position, long arg3) {
            // color selection select item
            arg1.setBackgroundColor(Color.GRAY);
        }
    });
}}
wingsraam
  • 187
  • 2
  • 16

5 Answers5

0

actually what the problem is when you swipe listview the items are shuffling.to avoid this problem put listview in scrollview. if you want code sample i can provide.

Sandeep Kumar
  • 350
  • 4
  • 18
0

Create your own adapter, in which every item has 'selected' flag, cleared by default. In click listener set flag for given item and force redraw. You should use RecuclerView, because it work faster. When view is inflated, check selection flag and set background accordingly

Alex Shutov
  • 3,217
  • 2
  • 13
  • 11
0

XML file

      <ScrollView
          android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginBottom="5dp"
    android:scrollbars="none"
    android:visibility="gone">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <ListView

            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="1dp"
            android:scrollbars="none"
            android:visibility="visible" />
    </LinearLayout>

</ScrollView>

java class

    listview.setAdapter(agentRequestAdapter);

    setListViewHeightBasedOnChildren(lvAgntRqstView);
         ////////////////////////////

    private static void setListViewHeightBasedOnChildren(ListView myListView) {
    try {
        ListAdapter myListAdapter = myListView.getAdapter();
        if (myListAdapter == null) {
            //do nothing return null
            return;
        }
        //set listAdapter in loop for getting final size
        int totalHeight = 0;
        for (int size = 0; size < myListAdapter.getCount(); size++) {
            View listItem = myListAdapter.getView(size, null, myListView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        //setting listview item in adapter
        ViewGroup.LayoutParams params = myListView.getLayoutParams();
        params.height = totalHeight + (myListView.getDividerHeight() * (myListAdapter.getCount() - 1));
        myListView.setLayoutParams(params);
        // print height of adapter on log
        Log.i("height of listItem:", String.valueOf(totalHeight));


    } catch (NullPointerException e) {

    }
}
Sandeep Kumar
  • 350
  • 4
  • 18
0

As in this answer by bhatt4982, you can set the attribute to make the option available to select multiple entries in the list:

First you can set in the listView itself like in this example

    listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    listView.setItemCanFocus(false);

Second you can declare it in your layout, or in your layout_simple_list_item_1.xml. Example:

    <ListView
    ...
    android:background="@drawable/your_drawable"
    android:checkMark="?android:attr/listChoiceIndicatorMultiple"/>

And then you can set the background in your custom drawable.

Source

Community
  • 1
  • 1
Horsty
  • 321
  • 6
  • 18
  • arg1.setBackgroundColor(Color.GRAY);// this code implements, when particular item click to set bgcolor and automatically another item selected.pls help – wingsraam Aug 25 '16 at 10:02
  • Hi Sir, I have one query about Multiselection in Listview on screen i have 20 item added in listview, but on current screen only showable 7 items others when i scroll the listview it will follow by appear now my query is when i multiselect the items like 2,3,6 its selected on current screen but same times after of 2nd page(scroll down) the items are selected without my knowledge (for Ex: screen 1 have 7 items but my selection is only 2,3,6 thats all but screen 2 (while scroll down) the 9,10,13 are selected there i don't kw why that item is selected on screen 2) how could u solve this issues? – wingsraam Aug 25 '16 at 11:08
0
public class MainActivity extends AppCompatActivity {

List<Items> data;
RecyclerView rv;
ActionMode actionMode;
ListAdapterr listAdapterr;
int countSelected;
int total;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    rv = (RecyclerView) findViewById(R.id.rv);
    rv.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
    CallAPI();

    rv.addOnItemTouchListener(new RecyclerItemClickListener(getApplicationContext(), rv, new RecyclerItemClickListener.OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {

            if (countSelected > 0)
            {
                if (actionMode == null)
                {
                    actionMode = MainActivity.this.startSupportActionMode(call);
                }
                toggleSelection(position);
                String s = countSelected + " " + "S" + " " + total ;
                actionMode.setTitle(s);

                if (countSelected == 0)
                {
                    actionMode.finish();
                }
            }else if (countSelected == 0)
            {
                Toast.makeText(MainActivity.this, "Ok", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onItemLongClick(View view, int position) {

            if (actionMode == null)
            {
                actionMode = MainActivity.this.startSupportActionMode(call);
            }
            toggleSelection(position);
            String s = countSelected + " " + "S" + " " + total ;
            actionMode.setTitle(s);

            if (countSelected == 0)
            {
                actionMode.finish();
            }
        }
    }));

}

ActionMode.Callback call = new ActionMode.Callback() {
    @Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        mode.getMenuInflater().inflate(R.menu.menu_item,menu);
        actionMode = mode;
        countSelected = 0;
        return true;
    }

    @Override
    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        return false;
    }

    @Override
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        return false;
    }

    @Override
    public void onDestroyActionMode(ActionMode mode) {
        if (countSelected > 0) {
            deselectAll();
        }
        actionMode = null;
    }
};

ArrayList<Items> selectedList = new ArrayList<>();

private void toggleSelection(int position) {
    data.get(position).isSelected = !data.get(position).isSelected;

    if (data.get(position).isSelected) {
        selectedList.add(data.get(position));
        countSelected++;
        total +=Integer.valueOf(data.get(position).getAmount());
    } else {
        selectedList.remove(data.get(position));
        countSelected--;
        total -= Integer.valueOf(data.get(position).getAmount());
    }
    listAdapterr.notifyDataSetChanged();
}

private void deselectAll() {
    for (int i = 0, l = data.size(); i < l; i++) {
        data.get(i).isSelected = false;
    }
    countSelected = 0;
    listAdapterr.notifyDataSetChanged();
}

RecyclerView:

   public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
public interface OnItemClickListener {
    void onItemClick(View view, int position);
    void onItemLongClick(View view, int position);
}

private OnItemClickListener mListener;
private GestureDetector mGestureDetector;

public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) {
    mListener = listener;

    mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            return true;
        }

        @Override
        public void onLongPress(MotionEvent e) {
            View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());

            if (childView != null && mListener != null) {
                mListener.onItemLongClick(childView, recyclerView.getChildAdapterPosition(childView));
            }
        }
    });
}

@Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
    View childView = view.findChildViewUnder(e.getX(), e.getY());

    if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
        mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
    }

    return false;
}

@Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
}

@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

}

}

Secret
  • 611
  • 1
  • 10
  • 29