如何使用listview获取选定的单选按钮标记

时间:2017-09-12 14:25:07

标签: android android-layout listview

我在我的片段中创建了一个单选按钮,现在尝试找到eventListener,当用户选择单选按钮时,我可以用它来获取单选按钮ID /标记。这是我的布局:

 <LinearLayout
            android:paddingBottom="5dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

    <LinearLayout
            android:id="@+id/zone_types_list_View"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:choiceMode="singleChoice"
            android:orientation="vertical"
            android:background="@drawable/room_type_border"/>
    </ScrollView>
    </LinearLayout>

片段:

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
     listView = (LinearLayout) rootView.findViewById(R.id.zone_types_list_View);
     ..
     ..
 }


private void addRadioButtons(final List<String> zoneTypesList) {
    if (getActivity() != null) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                radioGroup = new RadioGroup(mActivity);
                List<RadioButton> radioButtonsList = new ArrayList<RadioButton>();
                for (String ss : zoneTypesList) {
                    radioButton = new RadioButton(mActivity);
                    radioButton.setText(ss);
                    radioButton.setTag(ss.trim());

                    radioButtonsList.add(radioButton);
                    radioGroup.addView(radioButton);
                 }
                 listView.addView(radioGroup);
             }
        });
    }
}

我正在使用addRadioButtons(List<String>)在视图上添加动态单选按钮。有人可以告诉我当单选按钮选择并且可能获得单选按钮标签而不是仅位置或Id时,应该使用哪个组件来监听事件?

1 个答案:

答案 0 :(得分:1)

您可以使用CompoundButton.OnCheckedChangeListener

radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        String tag = (String) buttonView.getTag();
    }
});