android - 使用单选按钮制作ListView

时间:2014-08-04 21:47:05

标签: android xml listview android-listview android-radiobutton

我已经制作了一个带有无线电按钮的列表视图,但这些项目不像普通的无线电按钮那样,因为我认为没有无线电组将它们连接在一起。

我可以以编程方式将它们添加到不在xml中的radiogroup吗?我希望能够在用户按下不在列表视图中的按钮时找到选择的项目。

我试过这个却失败了,有人能帮助我吗?

这是我的片段:

public class DietTypeFragment extends Fragment implements AdapterView.OnItemClickListener, View.OnClickListener {
    Button Next;
    Button Back;
    private InteractionListener listener;
    ListView list;
    private static String[] DietList = {"Low Fat", "Low Carb", "Bodybuilder", "Balanced", "Diabetes", "Gluten Free", "Vegeterian"};
    private static String[] DietListSubTxt = {"For weight loss and the less active", "For weight loss and general fitness",
                             "For Strength building", "For all around fitness and nutrition",
                             "Carbohydrates monitored diet", "Diet excluding foods containing gluten", "Plant-based diet"};
    List<NameValuePair> DietType = new ArrayList<NameValuePair>();

    public DietTypeFragment() {
        // Required empty public constructor
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        Next = (Button) getActivity().findViewById(R.id.next_btn);
        Next.setOnClickListener(this);

        Back = (Button) getActivity().findViewById(R.id.back_btn);
        Back.setOnClickListener(this);

        listener = (InteractionListener) getActivity();

        list = (ListView) getActivity().findViewById(R.id.list_diet_type);

        // If you call this fragment more than once (press the back button) then you dont want to add the string again
        if (DietType.isEmpty()) {
            for(int i=0; i< DietList.length; i++) {
                DietType.add(new BasicNameValuePair(DietList[i], DietListSubTxt[i]));
            }
        }
        ArrayAdapter adapter = new ArrayAdapter (getActivity(), R.layout.simple_list_item_2_single_choice, android.R.id.text1, DietType) {

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                View view = super.getView(position, convertView, parent);
                TextView text1 = (TextView) view.findViewById(android.R.id.text1);
                TextView text2 = (TextView) view.findViewById(android.R.id.text2);

                NameValuePair data = DietType.get(position);

                text1.setText(data.getName());
                text2.setText(data.getValue());

                return view;
            }
        };
        list.setAdapter(adapter);
        list.setOnItemClickListener(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_diet_type, container, false);
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Log.d("DietTypeFrag",Integer.toString(view.getId()));
    }

    public void onStop() {
        super.onDetach();
        //listener = null;
    }
    @Override
    public void onClick(View view) {
        listener.DietTypeFragmentChangeScreen(view.getId());
        Log.d("DietTypeFrag","next or back clicked?");
    }
    public interface InteractionListener {
        public void DietTypeFragmentChangeScreen(int id);
    }
}

这是片段调用的xml布局:simple_list_item_2_single_choice

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:gravity="center_vertical"
    android:paddingStart="16dip"
    android:paddingEnd="12dip"
    android:minHeight="?android:attr/listPreferredItemHeightSmall"
    android:background="@android:color/transparent">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical"
        android:gravity="center_vertical">

        <TextView android:id="@android:id/text1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceListItem"
            android:textColor="?android:attr/textColorAlertDialogListItem"
            android:gravity="center_vertical|start"
            android:singleLine="true"
            android:ellipsize="marquee" />

        <TextView android:id="@android:id/text2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="?android:attr/textColorAlertDialogListItem"
            android:gravity="center_vertical|start"
            android:singleLine="true"
            android:ellipsize="marquee" />

    </LinearLayout>

    <RadioButton
        android:id="@+id/rdbtn_sc"
        android:layout_width="35dip"
        android:layout_height="wrap_content"
        android:paddingEnd="12dip"
        android:gravity="center_vertical"
        android:focusable="false"
        android:clickable="false" />

</LinearLayout>

然后还有另一个片段,它有自己的xml,包含后面和下一个按钮,但这不是问题的一部分。

1 个答案:

答案 0 :(得分:0)

您需要为您的列表视图使用CustomAdapter   以下是关键想法

当选中RadioButton时,我们必须调用notifyDataSet(),以便更新所有视图。 当检查RadioButton时,我们必须设置selectedPosition,以跟踪选择哪个RadioButton 视图在ListViews中被回收。因此,它们的绝对位置在ListView中发生了变化。因此,在ListAdapter#getView()内部,我们必须在每个RadioButton上调用setTag()。这允许我们在单击RadioButton时确定列表中RadioButton的当前位置。 RadioButton #setChecked()必须在getView()内部更新,以用于新的或预先存在的视图。 下面是我编写和测试的ArrayAdapter示例,以演示这些想法

public class MainActivity extends ListActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // I do no use these values anywhere inside the ArrayAdapter. I could, but don't.
    final Integer[] values = new Integer[] {1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,};

    ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this, R.layout.row, R.id.textview, values) {

        int selectedPosition = 0;

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;
            if (v == null) {
                LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = vi.inflate(R.layout.row, null);
                RadioButton r = (RadioButton)v.findViewById(R.id.radiobutton);
            }
            TextView tv = (TextView)v.findViewById(R.id.textview);
            tv.setText("Text view #" + position);
            RadioButton r = (RadioButton)v.findViewById(R.id.radiobutton);
            r.setChecked(position == selectedPosition);
            r.setTag(position);
            r.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    selectedPosition = (Integer)view.getTag();
                    notifyDataSetInvalidated();
                }
            });
            return v;
        }

    };
    setListAdapter(adapter);
}

}

这是原始主题:Android: Radio button in custom list view