在ListView中添加单选按钮

时间:2011-09-28 07:05:56

标签: android

我需要在ListView中添加RadioButton,事实上我已经尝试了,但我得到的问题是,当我点击单选按钮时,它会被奇妙地选中...但同时如果不希望选择该特定按钮......它仍然被选中。我在这里提供我的代码:

import android.app.ListActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class RadioInCustomListView extends ListActivity {

    ListView lv;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


        String[] names = new String[] { "Issues", "Request for Information",
                    "Contracts", "Purchase Orders", "Change Orders", "Proposals",
                    "Submittals" };
            lv = getListView();
            lv.setCacheColorHint(Color.TRANSPARENT);
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.radio_item, names);
            //this.setListAdapter (new ArrayAdapter<String>(RadioInCustomListView.this,R.layout.radio_item, names));
            setListAdapter(adapter);
    }

        protected void onListItemClick(ListView l, View v, int position, long id) {
            super.onListItemClick(l, v, position, id);
            Object o = this.getListAdapter().getItem(position);
            Toast.makeText(RadioInCustomListView.this, o.toString(), Toast.LENGTH_LONG).show();


            }
    }

我的xmls: 的 main.xml中:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<ListView  
    android:id="@+android:id/list"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    />
</LinearLayout>

radio_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RadioButton xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@android:id/text1"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:textAppearance="?android:attr/textAppearanceLarge"
  android:gravity="center_vertical"
  android:checkMark="?android:attr/listChoiceIndicatorSingle"
  android:paddingLeft="6dip"
  android:paddingRight="6dip"
/>

1 个答案:

答案 0 :(得分:2)

可能是此代码可以帮助您

ls.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_single_choice,list_sexuality));
ls.setChoiceMode(ListView.CHOICE_MODE_SINGLE);