List Item is not highlighted upon Selection (ListAdapter used)

Hi,
I am trying to create a Dialog with list items in it with the help of List Adapter.

Dialog is working fine.

ISSUE:-
→ Selected list row is NOT Highlighted for whichever list item “TextView.setBackgroundColor” is used
→ Selected list row is Highlighted for whichever list item “TextView.setBackgroundColor” is NOT used

I want all the list items highlighted upon Selection irrespective of background color (i am setting background color as BLACK)

Please suggest on this …

MainActivity.java


package com.example.testpro;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;
 public class MainActivity extends Activity {
	 
	 class Item {
	     String number;
	     int content;

	     public Item (String number, int content)
	     {	     
	        //this.number = "h";
	        //this.content = content;	        
	     }
	}
	 
	 
	 public void myListDialog()
		{
	    	final Item[] items = {
	    		    new Item("Email", android.R.drawable.ic_menu_add),
	    		    new Item("Facebook", android.R.drawable.ic_menu_delete),
	    		    new Item("...", 0),//no icon for this one
	    		    new Item("...", 0)//no icon for this one
	    		};

	    		ListAdapter adapter = new ArrayAdapter<Item>(
	    		    MainActivity.this,
	    		    android.R.layout.select_dialog_item,
	    		    android.R.id.text1,
	    		    items){
	    			
	    		        public View getView(int position, View convertView, ViewGroup parent) {
	    		            //User super class to create the View
	    		            View v = super.getView(position, convertView, parent);
	    		            TextView myView = (TextView)v.findViewById(android.R.id.text1);
	                        
	    		            
	    		            
	    		            //--------------------ISSUE AREA --------------------------------------------------
	    		            if( (position == 0) || (position == 2) )
	    		            {
	    		            	myView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.tick, 0, 0, 0);
	    		            	myView.setText("No Highlight on Selection");
	        		            
	    		            	myView.setTextColor(getResources().getColor(R.color.blue));
	    		            	myView.setBackgroundColor(getResources().getColor(R.color.grey));	            		            
	    		            }
	    		            if( (position == 1) || (position == 3) )
	    		            {
	    		            	myView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.error, 0, 0, 0);	        		            
	    		            	myView.setText("Highlight on Selection");
	    		            }
	    		            //--------------------ISSUE AREA --------------------------------------------------
	    		            
	    		            //Add margin between image and text (support various screen densities)
	    		            int dp5 = (int) (5 * getResources().getDisplayMetrics().density + 0.5f);
	    		            myView.setCompoundDrawablePadding(dp5);

	    		            return v;
	    		        }
	    		    };

	    		 new AlertDialog.Builder(MainActivity.this)
	    		    .setTitle("Choose Item")	    		    
	    		    .setAdapter(adapter, new DialogInterface.OnClickListener() {
	    		        public void onClick(DialogInterface dialog, int item) {
	    		        	Toast.makeText(MainActivity.this,"Selected Choice: "+item,Toast.LENGTH_SHORT).show();
	    		        }
	    		    }).show();
	    		    
	    	//-------------------------------------------------------------------------
		} 
	 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        Button pdring_btn=(Button)findViewById(R.id.btnpdring);
        pdring_btn.setOnClickListener(new OnClickListener() {
                  @Override
                  public void onClick(View v) {
                        myListDialog();                                          
                  }
            });
    }
}


strings.xml


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

    <color name="grey">#ACACAC</color>     
    <color name="blue">#0000BB</color>    
    <string name="app_name">testPro</string>
    <string name="action_settings">Settings</string>

</resources>

activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".AndroidGPSTrackingActivity" >

    <Button android:id="@+id/btnpdring"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Open Dialog"
        android:textColor="#000000"
        android:layout_centerInParent="true"/>

</RelativeLayout>


Create your own ArrayAdapter and modify the ‘items’ the adapter holds. Then notify the adapter the items have been updated. This will trigger a display update. The display update should grab the background color from the item and set it appropriately.

i have created my own array adapter only. i have posted it in the code. still selected list item is not highlighted.

can you post your ui as image…

List views are not trivial, they can be a royal pain when you need custom stuff. There are several ways of doing what you want, my way is just one of many. Since you are using android’s default layout, “android.R.layout.select_dialog_item”, there’s not much you can do. You have to override the BaseAdapter and then you can do just about any custom stuff. With dialog_rowlayout.xml you can customize your rows to the hilt.

dialog_layout.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/dialog_ListView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>
   
</LinearLayout>

dialog_rowlayout.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/dialog_LLO"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

       <ImageView
           android:id="@+id/dialog_ListViewIV"
           android:layout_width="45dp"
           android:layout_height="45dp"
           android:layout_gravity="center"
           android:layout_margin="10dp"
           android:src="@drawable/ic_launcher" />

       <TextView
           android:id="@+id/dialog_ListViewTV"
           android:layout_width="fill_parent"
           android:layout_height="fill_parent"
           android:layout_marginRight="10dp"
           android:gravity="center_vertical"
           android:paddingLeft="5dp"
           android:text="title"
           android:textSize="18sp" />

</LinearLayout>

MainActivity.java


public class MainActivity extends Activity {
   
   class Item {
       String number;
       int content;

       public Item (String number, int content)
       {       
          //this.number = "h";
          //this.content = content;         
       }
  }
   
   public void myListDialog()
    {
        final Item[] items = {
              new Item("Email", android.R.drawable.ic_menu_add),
              new Item("Facebook", android.R.drawable.ic_menu_delete),
              new Item("...", 0),//no icon for this one
              new Item("...", 0)//no icon for this one
          };

          ListAdapter adapter = new ArrayAdapter<Item>(
              MainActivity.this,
              android.R.layout.select_dialog_item,
              android.R.id.text1,
              items){
            
                  public View getView(int position, View convertView, ViewGroup parent) 
                  {
                      //User super class to create the View
                      View v = super.getView(position, convertView, parent);
                      TextView myView = (TextView)v.findViewById(android.R.id.text1);
                          
                      myView.setOnClickListener(new OnClickListener()
                      {
                       @Override
                       public void onClick(View v)
                       {
                         ((TextView) v).setTextColor(getResources().getColor(R.color.blue));
                       }
                       });
                      

                      
                      //--------------------ISSUE AREA --------------------------------------------------
                      if( (position == 0) || (position == 2) )
                      {
                        myView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_launcher, 0, 0, 0);
                        myView.setText("No Highlight on Selection");
                          
                        myView.setTextColor(getResources().getColor(R.color.blue));
                        myView.setBackgroundColor(getResources().getColor(R.color.grey));                             
                      }
                      if( (position == 1) || (position == 3) )
                      {
                        myView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_launcher, 0, 0, 0);                          
                        myView.setText("Highlight on Selection");
                      }
                      //--------------------ISSUE AREA --------------------------------------------------
                      
                      //Add margin between image and text (support various screen densities)
                      int dp5 = (int) (5 * getResources().getDisplayMetrics().density + 0.5f);
                      myView.setCompoundDrawablePadding(dp5);

                      return v;
                  }
              };

           new AlertDialog.Builder(MainActivity.this)
              .setTitle("Choose Item")              
              .setAdapter(adapter, new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int item) {
                    Toast.makeText(MainActivity.this,"Selected Choice: "+item,Toast.LENGTH_SHORT).show();
                  }
              }).show();
              
        //-------------------------------------------------------------------------
    } 
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        Button pdring_btn=(Button)findViewById(R.id.btnpdring);
        pdring_btn.setOnClickListener(new OnClickListener() {
                  @Override
                  public void onClick(View v) {
                 //   myListDialog();                                          
                    myCustomListDialog();                                          
                  }
            });
    }

 
 
 
 
 
 
 
 
    private void myCustomListDialog()
    {
      final Dialog dialog = new Dialog(this);
      
      dialog.setContentView(R.layout.dialog_layout);
      dialog.getWindow().setLayout(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
      dialog.setTitle("Choose Item");
      
      
      List<String> myArray = new ArrayList<String>();

      myArray.add("No Highlight on Selection");
      myArray.add("Highlight on Selection");
      myArray.add("No Highlight on Selection");
      myArray.add("Highlight on Selection");

      final ListView myListView = (ListView)dialog.findViewById(R.id.dialog_ListView);
      myListView.setAdapter(new MyCustomAdapter(myArray));

      myListView.setOnItemClickListener(new OnItemClickListener()
      {
        @Override
        public void onItemClick(AdapterView<?>arg0,View arg1,int arg2,long arg3)
        {
          arg1.setBackgroundColor(Color.parseColor("#ADD8E6"));
          dialog.dismiss();     
        }
      });

      dialog.show();    
    }
    
    
    
    
    
    class MyCustomAdapter extends BaseAdapter
    {
      List<String>   theArray;
      LayoutInflater inflater  = getLayoutInflater();
      TextView       textview;
      ImageView      imageview;
      LinearLayout   linearlayout;

      MyCustomAdapter(List<String> myArray)
      {
        theArray = myArray;
      }

      public View getView(int position, View convertView, ViewGroup parent)
      {
        View row     = convertView; 
        
        if(row==null)
           row = inflater.inflate(R.layout.dialog_rowlayout, parent, false);
          
        linearlayout = (LinearLayout)row.findViewById(R.id.dialog_LLO);
        imageview    = (ImageView)   row.findViewById(R.id.dialog_ListViewIV);
        textview     = (TextView)    row.findViewById(R.id.dialog_ListViewTV);
        
        textview.setText(theArray.get(position));

        textview.setTextColor(getResources().getColor(R.color.blue));

        if((position==0)||(position==2))
            linearlayout.setBackgroundColor(getResources().getColor(R.color.grey));
        
        return (row);
      }

      public int getCount(){return theArray.size();}
      public String getItem(int position){return null;}
      public long getItemId(int position){return position;}
    }

 
 
 }

Thanks so much mrBruce. It took me time to look at your post as i was damm busy in working on a android app.
Thanks so much for the solution again.

No problem :slight_smile: