0

I have made a listview with radiobuttons, but the items don't behave like normal radiobuttons because there is no radiougroup that bonds them together I think.

Can I add them to a radiogroup that is not in the xml programatically? I want to be able to find which item is selected when the user presses a button that is not in the listview.

I have tried this but failed, can someone help me?

This is my fragment:

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);
    }
}

and this is the xml layout that that the fragment calls: 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>

And then there is another fragment with its own xml that contains the back and next buttons, but that is not part of the problem.

Treebeard
  • 64
  • 1
  • 7

1 Answers1

0

You need to CustomAdapter for your listview Or Here are the key ideas

when a RadioButton is checked we must call notifyDataSet(), so that all views get updated. when a RadioButton is checked we must set a selectedPosition, to keep track of which RadioButton is selected Views are recycled inside ListViews. Therefore, their absolute position changes in the ListView. Therefore, inside ListAdapter#getView(), we must call setTag() on each RadioButton. This allows us to determine the current position of the RadioButton in the list when the RadioButton is clicked. RadioButton#setChecked() must be updated inside getView() for new or pre-existing Views. Here is an example ArrayAdapter I wrote and tested in order to demonstrate these ideas

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);
}

}

Here is original thread : Android: Radio button in custom list view

Community
  • 1
  • 1
cantas
  • 104
  • 1
  • 14