简体   繁体   中英

Change text color of selected item of Listview in Android

I am creating an application in which I have one Listview . When I select item of this Listview , one Alert dialog appears.
In this Alert dialog, there is also one Listview . Items in this Listview are depends on the user inputs.
Now, when I select item in this listview, text color must be changed and when I again select this item, text color must change to its original color.
What should be done?

Add a map to your class that tracks your selected items:

HashMap <Integer, Boolean> selectionStates = new HashMap <String, Boolean>();

Use a custom adapter for your ListView. In getView, set the color according to the value in your map:

if (selectionStates.contains(position) && selectionStates.get(position){
  yourTextView.setTextColor(selectedColor);
}
else {
  yourTextView.setTextColor(normalColor);
}

Add an onItemClickListener to your ListView eg in onCreate:

yourListView.setOnItemClickListener(){
  public void onItemClick (AdapterView<?> parent, View view, int position, long id){
    boolean alreadySelected = false;
    if (selectionStates.contains(position) && selectionStates.get(position) alreadySelected = true;
    selectionStates.put(position, !alreadySelected);

    TextView yourTextView = (TextView) view.findViewById(R.id.yourItemTextView);

    if (selectionStates.contains(position) && selectionStates.get(position){
      yourTextView.setTextColor(selectedColor);
    }
    else {
      yourTextView.setTextColor(normalColor);
    }
  }
};

This will not only change the color of an item immediately after it has been selected, but also retain the color after scrolling.

As an adapter, you could extend ArrayAdapter:

yourListView.setAdapter(new ArrayAdapter<WhatEverClass>(ArgumentsHere){
  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
      View view = super.getView(position, convertView, parent);
      TextView yourTextView = (TextView) view.findViewById(R.id.yourItemTextView);

      if (selectionStates.contains(position) && selectionStates.get(position){
         yourTextView.setTextColor(selectedColor);
      }
      else {
         yourTextView.setTextColor(normalColor);
      }
  }
});

Please note that I did not test this code, but it should at least give you an idea of what your code should look like.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM