简体   繁体   English

android单选列表选择问题?

[英]android single choice list selection problem?

friends, 朋友们,

i am using following code to display list with radio buttons now i want to select specific radio button of list by default so using setSelection property which does not work. 我正在使用以下代码显示带有单选按钮的列表现在我想默认选择列表的特定单选按钮,因此使用setSelection属性不起作用。

final String [] items=new String[]{"Item1","Item2","Item3","Item4"};
            ArrayAdapter<string> ad=new ArrayAdapter<string>(this,android.R.layout.simple_list_item_single_choice,items);
            list=(ListView)findViewById(R.id.List);
            list.setAdapter(ad);

list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
list.setSelection(2);
    list.setOnItemClickListener(new OnItemClickListener()
            {

       public void onItemClick(AdapterView arg0, View arg1, int arg2,
         long arg3) {
        // TODO Auto-generated method stub
        TextView txt=(TextView)findViewById(R.id.txt);
        txt.setText(list.getItemAtPosition(arg2).toString());


       }

            }
            );

please guide what mistake am i doing? 请指导我在做什么错误?

你在寻找:

list.setItemChecked(2, true);

I might be completely off, but I think setSelection doesn't necessarely checks your item (as in checkbox, or radio), it navigates to it though. 我可能完全关闭了,但我认为setSelection不必检查你的项目(如复选框或无线电),但它会导航到它。

As a workaround (maybe there is a more elegant solution) you can extend ArrayAdapter and set checked manually in a getView() method. 作为一种解决方法(可能有一个更优雅的解决方案),您可以扩展ArrayAdapter并在getView()方法中手动设置检查。

Add something like this to your class: 在课堂上添加以下内容:

private static class MArrayAdapter extends ArrayAdapter<String> {
    public Adapter(final Context context, final String[] objects) {
        super(context, android.R.layout.simple_list_item_single_choice, objects);
    }

    @Override
    public View getView(final int position, final View convertView, final ViewGroup parent) {
        final CheckedTextView view = (CheckedTextView) super.getView(position, convertView, parent);
        view.setChecked(position == 2);
        return view;
    }

}

And change your way of getting an adapter to new MArrayAdapter(this, items); 并改变你的适配器到new MArrayAdapter(this, items);

PS On my previous comment, my mistake, you better call setChoiceMode (it's just in my app, I call notifyDataSetChanged, so I don't really need it). PS在我之前的评论中,我的错误,你最好调用setChoiceMode(它只是在我的应用程序中,我调用notifyDataSetChanged,所以我真的不需要它)。 I think your'r up to some weird behaviour without choice mode. 我认为你没有选择模式会有一些奇怪的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM