Dynamically Changing Color (List Element) TextView in Listview

I am using ListView as shown below in filename browse.xml.

<ListView
   android:id="@+id/listView1"
   android:layout_width="250dp"
   android:layout_height="match_parent"
   android:layout_alignParentLeft="true"
   android:layout_below="@+id/relativeLayout1" >

</ListView>

And I populate this listView inside the onCreate () method as:

files1=new ArrayList<String>();
File sdcard=Environment.getExternalStorageDirectory();
files1 =  getListFiles(new File(sdcard.getAbsolutePath()+File.separatorChar)); 
ArrayAdapter<String> fileList =new ArrayAdapter<String>(this, R.layout.row,files1);

setListAdapter(fileList);

row.xml is shown below:

<?xml version="1.0" encoding="utf-8"?>
<TextView 
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/rowtext"
   android:layout_width="fill_parent"
   android:layout_height="40dp"
   android:textSize="20dp" 
   android:textColor="#000000"   
   android:background="#FFFFFF"/>

This whole program shows all sdcard files in listView and when I click on any list, I save this file name in sharedPrefernce. Now I want to change the text color of the file name (list items) in the ListView which are in SharedPrefernce ..

[EDIT]: here I use the default constructor ArrayAdapter to list all the elements in the list

Pls offer me something .. Thanks ..

+5
source share
2 answers

We can dynamically change the dynamic text for a list item in the getView () adapter.

public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;

    if (row == null) {
        row = LayoutInflater.from(parent.getContext()).inflate(R.layout.row, null);
    }

    TextView listTitle = (TextView) row.findViewById(R.id.rowtext);
    listTitle.setTextColor(Color.parseColor("#405478"));

    return listTitle;
}
+3

ArrayList<boolean> saved = new ArrayList<boolean>();

0 files1.size() FALSE

, itemClickListener TRUE at position clicked , saved.set(position,TRUE);

notifyDataSetChanged();, TRUE .

getView

public View getView(int position, View convertView, ViewGroup parent) { 

    View row = convertView; 
    position = = getItemViewType(position);
    if(row==null){ 
        row = LayoutInflater.from(parent.getContext()).inflate(R.layout.row, null); 
    } 

    TextView listTitle = (TextView) row.findViewById(R.id.rowtext); 
    if(saved.get(position)==TRUE)
    {
            listTitle .setTextColor(Color.parseColor("#405478")); 
    }
}

,

@Override
public int getItemViewType(int position) {

return position;
}

@Override
public int getViewTypeCount() {
return files1.size();
}
+2

All Articles