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

13

11

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.

Swerve answered 6/3, 2012 at 3:35 Comment(2)
Down vote for not providing some snippet to help you out, Without looking into your code SO can't guess where are you stuck.Recourse
See also for a complete example: #30409921Soricine
R
7

You can do this by

yourListView.setSelection(0);
yourListView.getSelectedView().setSelected(true);

I hope this will help you

Rizika answered 6/3, 2012 at 3:43 Comment(2)
@ChiragPatel will u please help me on this issue #18100256Leeanneleeboard
@ChiragPatel Can we select List automatically into string variable please help me how can i select list item with the help of String valuePlaysuit
Y
11
yourlist.setItemChecked(position,true)
Yarvis answered 26/3, 2013 at 14:0 Comment(0)
R
7

You can do this by

yourListView.setSelection(0);
yourListView.getSelectedView().setSelected(true);

I hope this will help you

Rizika answered 6/3, 2012 at 3:43 Comment(2)
@ChiragPatel will u please help me on this issue #18100256Leeanneleeboard
@ChiragPatel Can we select List automatically into string variable please help me how can i select list item with the help of String valuePlaysuit
N
4

This work for me. I hope this will help you. :)

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

    // do someting...
    if(position == 0){
        mListView.performItemClick(convertView, 0, 0);
    }

 }

now i found another good way to implement this.

  • Firstly,you should set ListView android:choiceMode=singleChoice
  • Secondly,just go ahead as follow,

        int defaultPositon = 0;
        int justIgnoreId = 0;
        mListView.setItemChecked(defaultPositon, true);
        mListView.performItemClick(mListView.getSelectedView(), defaultPositon, justIgnoreId);
    
Neurotic answered 1/8, 2014 at 6:52 Comment(1)
This works. One problem solved, now next one: selected item is not getting highlighted. WTF Android!Ene
B
2
//put the below code in get view function 
if(position==0)
{
    convertView.setSelected(true); 
}
Billye answered 6/3, 2012 at 4:27 Comment(0)
P
2

I think this will work as we have given 0 index of array to listView

ListView.setSelection(0);
Pandora answered 6/3, 2012 at 10:0 Comment(0)
C
1

Create an onItemClickListener then use this snippet, filling in the appropriate values:

listView.performItemClick(View view, int position, long id);

See the docs for further detail.

Crosswind answered 6/3, 2012 at 3:44 Comment(1)
Maybe you should provide some code in you question to show us how you are attempting it.Crosswind
P
1

You can call listview.setSelection(0);. Just make sure you are calling this after poplulating your List. If you call it before populating your List it will not work, because it won't have any data at that time.

Peppi answered 6/3, 2012 at 4:39 Comment(3)
I think your answer is suitable and helpful, but it doesn't work when I put it in my code where in think the list have been populated.Maybe something wrong in other place of the code......Swerve
It would be better if you can post code how you are writing it.Peppi
@LalitPoptani can u help me on this #18100256Leeanneleeboard
B
1

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);
Banister answered 28/6, 2015 at 5:22 Comment(0)
F
0

This works if you want to click it to get additional event handling done:

listView.getAdapter().getView(position, null, null).performClick();
Fabricant answered 13/1, 2014 at 10:32 Comment(0)
U
0

You can fix it like this.

//set list adapter, then
lv.setItemChecked(1, true);//position 1
lv.setSelection(1);//position 1

Update XML layout with single choice.

<ListView
    android:id="@+id/lv"
    android:layout_width="match_parent"
    android:layout_height="match_parent"  
    android:background="@drawable/list_item_background"
    android:cacheColorHint="#FFFFFF"
    android:choiceMode="singleChoice"
    android:dividerHeight="1dip" >
</ListView>

and set listview background XML as list_item_background.xml,

<?xml version="1.0" encoding="utf-8"?>
     <selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:drawable="@drawable/bg_list_default"   android:state_activated="false"/>
     <item android:drawable="@drawable/bg_list_pressed" android:state_pressed="true"/>
     <item android:drawable="@drawable/bg_list_pressed" android:state_activated="true"/>

Underthecounter answered 3/4, 2014 at 10:47 Comment(0)
I
0

THIS WORKS FOR ME.You have to make custom adapter.

     First Create Modal Class

        public class FilterBean {

         String filter_catagory;
                 boolean isSelected;

            public boolean isSelected() {
                return isSelected;
            }

            public void setSelected(boolean selected) {
                isSelected = selected;
            }

          public String getFilter_catagory() {
                return filter_catagory;
            }

            public void setFilter_catagory(String filter_catagory) {
                this.filter_catagory = filter_catagory;
            }

        }


    In Adapter Class

    @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            convertView = layoutInflater.inflate(R.layout.size_name_indicator, null);
            txt = (TextView) convertView.findViewById(R.id.key_textView);
            txt.setText(getItem(position).getFilter_catagory());

            if(getItem(position).isSelected()){
                txt.setBackgroundColor(context.getResources().getColor(R.color.transparent));
            }else {

                txt.setBackgroundColor(context.getResources().getColor(R.color.colorWhite));
            }


            return convertView;
        }

     public void updateNameBean(String key,boolean checked)
        {

            for(int i=0;i<getCount();i++)
            {
                FilterBean filterBean =  getItem(i);
                if(filterBean.getFilter_catagory().equals(key))
                {
                    filterBean.setSelected(checked);
                }else {
                    filterBean.setSelected(false);
                }
            }
            notifyDataSetChanged();
        }

In Filter Activity or Fragment

 filter_listView.setAdapter(filterNameAdapter);
               filterNameAdapter.updateNameBean(filterNameAdapter.getItem(0).getFilter_catagory(),true);
        filter_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                String key = filterNameAdapter.getItem(position).getFilter_catagory();
                filterNameAdapter.updateNameBean(filterNameAdapter.getItem(position).getFilter_catagory(),true);

            }
        }); 
Ilyssa answered 17/10, 2016 at 5:39 Comment(0)
L
0

I have used data binding to solve this,

using the following codebehind:

private List<Unit> _units;
private Unit _selectedUnit;
public Unit selectedUnit{
  get{
    if (_selectedUnit is null){
      return _units.Count > 0 ? _units[0] : null;
    }else{
      return _selectedUnit;
    }
  }
  set{
    if (_selectedUnit != value){
      _selectedUnit = value;
      OnPropertyChanged("selectedUnit");
    }
  }
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName){
  var changed = PropertyChanged;
  if (changed != null){
    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
  }
}

and XAML

<ListView ItemsSource="{Binding units}"
          SelectedItem="{Binding selectedUnit, Mode=TwoWay}">
Lifeordeath answered 19/2, 2019 at 12:4 Comment(0)
A
-1
if(position == 0){
        // This is the first item, you need to select this
        //rowview which u inflate under getview 
        rowView.performClick();

    }

i think this will help you . it works for me

Associationism answered 28/11, 2017 at 12:14 Comment(1)
this will fail because position 0 can call n number of time when listview will get scroll.Oram

© 2022 - 2024 — McMap. All rights reserved.