Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make the first item of a ListView to be selected as default at startup?

There is a ListView in my App and the ListView has a selector. I want to make the first item of this ListView to be selected as default at the very startup of App, How? Can anyone give some tips? THX a lot.

like image 342
acoustic Avatar asked Mar 06 '12 03:03

acoustic


2 Answers

yourlist.setItemChecked(position,true)
like image 95
Jachu Avatar answered Nov 10 '22 00:11

Jachu


Below solution works for me:

Setting background/View Id on get View & using the setOnItemClickListener of the List View

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View v = convertView;
    if (v == null) {
        LayoutInflater vi = (LayoutInflater)
                ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = vi.inflate(R.layout.listitems, null);
    }
    ListItem m = items.get(position);

    if (m != null) {

        TextView txt = (TextView)v.findViewById(R.id.textView);
        txt.setText(m.Item);

    }

    // set selected item
    LinearLayout ActiveItem = (LinearLayout) v;
    v.setId(position);
    if (position == GetDeviceDetails.selectedsize)
    {
        ActiveItem.setBackgroundColor(0xFF7F8184);
    }
    return v;
}

In the Activity on Create :

listView1.setOnItemClickListener(
            new AdapterView.OnItemClickListener() {
                public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
                    adapter.findViewById(GetDeviceDetails.selectedsize).setBackgroundColor(0xFFFFFFF);
                    GetDeviceDetails.selectedsize = position;
                    adapter.findViewById(position).setBackgroundColor(0xFF7F8184);
                    Log.d("Selected Id", "" + v.getId());
                    Log.d("find Selected Id", "" + adapter.findViewById(0));
                }
            });
    listView1.setSelection(0);
    listView1.setItemChecked(0, true);
like image 26
Murali Avatar answered Nov 10 '22 01:11

Murali