在 ListView 中默认选择一行并突出显示所选行 Android

Posted

技术标签:

【中文标题】在 ListView 中默认选择一行并突出显示所选行 Android【英文标题】:Default Selection of a Row in the ListView and HighLight the selected Row Android 【发布时间】:2013-08-08 14:46:03 【问题描述】:

我有 2 个列表视图。我想在活动开始时默认选择两个列表视图的第一行。我用谷歌搜索我发现了这个

onewaydata=new OneWayFlightResult(this, flightData);        
    onewayListView.setAdapter(onewaydata);
    onewayListView.setSelection(0);

    onewayListView.getSelectedView().setSelected(true);

但这对我不起作用

这是我拥有的两个 ListView

<LinearLayout
         android:layout_
         android:layout_
         android:layout_above="@+id/footerLayout"
         android:layout_below="@+id/sortFlightLayouts"
         android:orientation="horizontal" >

        <ListView
            android:id="@+id/lvDepartures"
            android:layout_weight="1"
            android:layout_marginLeft="5dp"
            android:layout_
            android:layout_/>
        <View
            android:layout_
            android:layout_
            android:background="@android:color/darker_gray" />
        <ListView
             android:id="@+id/lvArrivals"
             android:layout_weight="1"
             android:layout_marginLeft="5dp"
             android:layout_
             android:layout_/>

    </LinearLayout>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_
    android:background="@color/change_text_color"
    android:layout_ >
</RelativeLayout>

然后是change_text_color.xml

<?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:state_pressed="true"
           android:color="#E5FFED" /> <!-- pressed -->
     <item android:state_focused="true"
           android:color="#E5FFED" /> <!-- focused -->
     <item android:color="#EEE9E9" /> <!-- default -->
 </selector>

抛出异常

08-07 15:58:45.138: E/AndroidRuntime(3152): FATAL EXCEPTION: main
08-07 15:58:45.138: E/AndroidRuntime(3152): java.lang.RuntimeException: Unable to start activity ComponentInfocom.example.gridtestproject/com.example.gridtestproject.TestActivity: android.view.InflateException: Binary XML file line #217: Error inflating class android.widget.ListView
08-07 15:58:45.138: E/AndroidRuntime(3152):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2211)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at android.app.ActivityThread.access$600(ActivityThread.java:149)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1300)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at android.os.Looper.loop(Looper.java:153)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at android.app.ActivityThread.main(ActivityThread.java:4987)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at java.lang.reflect.Method.invokeNative(Native Method)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at java.lang.reflect.Method.invoke(Method.java:511)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at dalvik.system.NativeStart.main(Native Method)
08-07 15:58:45.138: E/AndroidRuntime(3152): Caused by: android.view.InflateException: Binary XML file line #217: Error inflating class android.widget.ListView
08-07 15:58:45.138: E/AndroidRuntime(3152):     at android.view.LayoutInflater.createView(LayoutInflater.java:613)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at android.view.LayoutInflater.onCreateView(LayoutInflater.java:660)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:685)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:749)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:258)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at android.app.Activity.setContentView(Activity.java:1867)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at com.example.gridtestproject.TestActivity.onCreate(TestActivity.java:34)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at android.app.Activity.performCreate(Activity.java:5020)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
08-07 15:58:45.138: E/AndroidRuntime(3152):     ... 11 more
08-07 15:58:45.138: E/AndroidRuntime(3152): Caused by: java.lang.reflect.InvocationTargetException
08-07 15:58:45.138: E/AndroidRuntime(3152):     at java.lang.reflect.Constructor.constructNative(Native Method)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at android.view.LayoutInflater.createView(LayoutInflater.java:587)
08-07 15:58:45.138: E/AndroidRuntime(3152):     ... 25 more
08-07 15:58:45.138: E/AndroidRuntime(3152): Caused by: android.content.res.Resources$NotFoundException: File res/drawable-hdpi/item_selected.xml from drawable resource ID #0x7f02000c
08-07 15:58:45.138: E/AndroidRuntime(3152):     at android.content.res.Resources.loadDrawable(Resources.java:1959)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at android.content.res.TypedArray.getDrawable(TypedArray.java:601)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at android.view.View.<init>(View.java:3343)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at android.view.ViewGroup.<init>(ViewGroup.java:433)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at android.widget.AdapterView.<init>(AdapterView.java:235)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at android.widget.AbsListView.<init>(AbsListView.java:781)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at android.widget.ListView.<init>(ListView.java:147)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at android.widget.ListView.<init>(ListView.java:143)
08-07 15:58:45.138: E/AndroidRuntime(3152):     ... 28 more
08-07 15:58:45.138: E/AndroidRuntime(3152): Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #4: <item> tag requires a 'drawable' attribute or child tag defining a drawable
08-07 15:58:45.138: E/AndroidRuntime(3152):     at android.graphics.drawable.StateListDrawable.inflate(StateListDrawable.java:178)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:881)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at android.graphics.drawable.Drawable.createFromXml(Drawable.java:818)
08-07 15:58:45.138: E/AndroidRuntime(3152):     at android.content.res.Resources.loadDrawable(Resources.java:1956)
08-07 15:58:45.138: E/AndroidRuntime(3152):     ... 35 more

所以请建议我如何在列表视图上进行默认选择。

【问题讨论】:

【参考方案1】:

而不是 your_list_view.setSelection(0); 试试 your_list_view.setItemChecked(0,true);

【讨论】:

【参考方案2】:

试试这个,它应该可以解决问题:

your_list_view.post(new Runnable() 

        @Override
        public void run() 
           your_list_view.setSelection(0);          
           
        );

更新:请看一下

    class YourAdapter extends BaseAdapter

            @Override
            public int getCount() 
                // TODO Auto-generated method stub
                return 0;
            

            @Override
            public Object getItem(int arg0) 
                // TODO Auto-generated method stub
                return null;
            

            @Override
            public long getItemId(int arg0) 
                // TODO Auto-generated method stub
                return 0;
            

            @Override
            public View getView(int position, View convertView, ViewGroup arg2) 
                View view = convertView;

                if(position == 0)
                    // This is the first item, you need to select this
                    view.setSelected(true);

                
                // Do whatever you want here
                return view;
            

        

在 XML 中:

<ListView
            android:id="@+id/lvDepartures"
            android:layout_weight="1"
            android:layout_marginLeft="5dp"
            android:listSelector="@null" <!--Here is the thing you need-->
            android:layout_
            android:layout_/>
        <View
            android:layout_
            android:layout_
            android:background="@android:color/darker_gray" />
        <ListView
             android:id="@+id/lvArrivals"
             android:layout_weight="1"
             android:layout_marginLeft="5dp"
             android:listSelector="@null" <!--Here is the thing you need-->
             android:layout_
             android:layout_/>

在您的 item-row-xml 中:

    <LinearLayout
             android:layout_
             android:layout_
             android:background="@drawable/item_row_selector"> <!--Here is the thing you need-->
    <!--Your item layout here-->
    </LinearLayout>

最后你需要实现自己的 item_row_select 状态为“selected”。

希望这会有所帮助。

【讨论】:

哦,对不起,我的错误,你的意思是前 2 个项目被“选中”(按下状态)?您可以在您的适配器中这样做,当您创建行视图时,在返回视图(仅第一个位置)之前,只需 view.setSelected(true)。这样,您需要删除列表选择器并为每一行实现行选择器。请尝试。 不,我想让列表视图的第一行默认被选中,请给我示例代码 好的,我明白了,尝试这样做your_list_view.performItemClick(null, 0, 0);。希望这行得通。 同样不工作,基本上我想在创建时获得默认选择,并突出显示选中的列表视图 schemas.android.com/apk/res/android"> 【参考方案3】:
**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 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);

            
        ); 

【讨论】:

以上是关于在 ListView 中默认选择一行并突出显示所选行 Android的主要内容,如果未能解决你的问题,请参考以下文章

选择其他按钮时,ListView 突出显示所选项目颜色不会保持不变

Android ListView 所选项目保持突出显示

如何在Android中的ListView中突出显示行?

当所选行是最后一行之前的行时自动滚动表格

反复在闪亮的renderTable中突出显示一行

突出显示 ListView 和 ListBox 控件中的第一行