Android - Radio Button in listView?

前端 未结 2 958
一向
一向 2021-01-06 05:13

I have a scenario that we should have a single choice mode radio button in listview. when i am click on the radiobutton it should go to enable state. when i am click on the

2条回答
  •  孤街浪徒
    2021-01-06 05:35

    One way you can but I don't know it's perfect or not.

    track the position id of the listview on which the radio button was checked now when you click on the another radio button then implement the setOnCheckedChangeListener(listener) and check the position which was already check and uncheck that radiobutton.

    You can store the status of radio button into the custom model(Model which contains the controls like textview, imageview, radiobutton etc for listview single row) which was added into the listview

    check this article for using model and handle the component into the listview in this given an example of checkbox

    Update

    I think you can get tag like this way

    ((View)((ViewGroup)listview.getItemAtPosition(0)).getTag()).getTag();
    or
    ((Button)l.getItemAtPosition(0)).getTag();
    

    update 2

    suppose this is your adapter and arraylist object

    private List list_model = new ArrayList();
    
    private ArrayAdapter modelAdapter;
    

    you Model class look like this

    private class Model{
        private String text1 = "";
        private boolean isChecked   = false;
    
        public Model(String text1){
            this.text1 = text1;
            isChecked = false;
        }
    }
    

    your viewholder

    private static class ViewHolder{
        TextView textView;
            RadioButton radioBtn;
    }
    

    pass the listmodel to this CustomAdapter class in constructor

    private List list;
    private Context context;
    
    public CustomAdapter(Context context, List list){
        super(context,R.layout.list_layout,list);
        this.list = list;
        this.context = context;
    }
    

    now in getView()

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = null;
    
        if(convertView == null){
            LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.gcalendar_list_layout, null);
            final ViewHolder viewHolder = new ViewHolder();
            viewHolder.textView = (TextView) view.findViewById(R.id.text1);
            viewHolder.radioBtn = (RadioButton) view.findViewById(R.id.radioBtn);
            viewHolder.radioBtn.setOnCheckedChangeListener(new OnCheckedChangeListener() {
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    Model element = (Model) viewHolder.checkBox.getTag();
                    element.isChecked = buttonView.isChecked();
                    boolean isChecked = true;
                    for(int i=0;i

提交回复
热议问题