GMX GMX - 13 days ago 7
Android Question

Highlighted an item of a ListView on start

Following this post i do that:

In my ListView I set the background color of the selected item like this:

<ListView
android:id="@+id/list_date"
android:choiceMode="singleChoice"
android:listSelector="#666666"
/>


When the user click an item on my list it stay highlighted, nice.

Now I want pre-select (highlight) an item of the list on start.I tried with that:

list_date.performItemClick(list_date, 0, list_date.getItemIdAtPosition(0));


but don't work. How can i do that?




Final working code:

TextView txtv,txtv2;
arrayAdapter = new ArrayAdapter<String>(HistoryActivity.this, R.layout.row, R.id.textViewList, date) {
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.row, parent, false);
}
txtv = (TextView) convertView.findViewById(R.id.textViewList);
txtv.setText(date.get(position));
if(position == 0){
txtv.setBackgroundColor(Color.parseColor("#93581c"));
txtv2 = (TextView) convertView.findViewById(R.id.textViewList);
}
return convertView;
}
};

list_date.setAdapter(arrayAdapter);

list_date.setOnItemClickListener(new AdapterView.OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {

if (position!=0)
txtv2.setBackgroundColor(Color.TRANSPARENT);
........
........
}
}

Answer

You can apply the background color manually in your adapter :

arrayAdapter = new ArrayAdapter<String>(HistoryActivity.this, R.layout.row, R.id.textViewList, array) {
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.R.layout.row, parent, false);
            }
            TextView tv = (TextView) convertView.findViewById(R.id.textViewList);
            tv.setText(array[position]);
            if(position == 0)
                tv.setBackgroundColor(Color.parseColor("#666666"));
            return convertView;
        }
    };
Comments