【问题标题】:android - making ListView with radio buttons workandroid - 使用单选按钮制作 ListView
【发布时间】:2014-08-04 21:47:05
【问题描述】:

我已经用单选按钮制作了一个列表视图,但是这些项目的行为不像普通的单选按钮,因为我认为没有将它们结合在一起的 radiougroup。

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

我试过这个但失败了,有人可以帮助我吗?

这是我的片段:

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 的片段,其中包含后退和下一步按钮,但这不是问题的一部分。

【问题讨论】:

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


    【解决方案1】:

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

    检查radiobutton时,我们必须调用NotifyDataset(),以便所有视图都更新。 检查RADIOButton时,我们必须设置一个选择的位置,以跟踪选择了哪个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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多