【问题标题】:Radio Buttons Deselected on scrolling in custom listview在自定义列表视图中滚动时取消选择单选按钮
【发布时间】:2016-08-16 19:08:46
【问题描述】:

在自定义列表视图中滚动时取消选择单选按钮 我已经制作了添加的自定义列表视图 自动添加运行时单选按钮 但它在滚动时取消选择

下面给出的适配器、主类和活动文件的代码

布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:background="@drawable/gradient11"
              android:layout_width="match_parent" android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <RadioGroup
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <RadioButton
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="option one is selected now so you can"
                android:textColor="#00ff00"
                android:id="@+id/op1"/>

            <RadioButton
                android:checked="true"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="op2"
                android:textColor="#00ff00"
                android:id="@+id/op2"/>

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="op3"
                android:textColor="#00ff00"
                android:id="@+id/op3"/>

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="op4"
                android:textColor="#00ff00"
                android:id="@+id/op4"/>

        </RadioGroup>

    </LinearLayout>

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/quest"
        android:textColor="#e2000000"/>

</LinearLayout>

适配器文件

package com.patel.ravin.com.domparsing;

    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.RadioButton;
    import android.widget.TextView;

    import java.util.ArrayList;

    /**
     * Created by lenovo on 08-08-2016.
     */
    public class Adpt extends BaseAdapter
    {
        Context context;
        ArrayList<MyBean> arrayList;

        public Adpt(Context context,ArrayList<MyBean> arrayList)
        {
            this.context=context;
            this.arrayList=arrayList;
        }
        @Override
        public int getCount() {
            return arrayList.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int i, View view, ViewGroup parent) {

            LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = layoutInflater.inflate(R.layout.listview, null);

            TextView txtFName = (TextView) view.findViewById(R.id.qid);
            TextView txtLName = (TextView) view.findViewById(R.id.quest);
            RadioButton op1=(RadioButton)view.findViewById(R.id.op1);
            RadioButton op2=(RadioButton)view.findViewById(R.id.op2);
            RadioButton op3=(RadioButton)view.findViewById(R.id.op3);
            RadioButton op4=(RadioButton)view.findViewById(R.id.op4);


            MyBean myBean = arrayList.get(i);
            txtFName.setText("" + myBean.getQid());
            txtLName.setText("   Answer= " + myBean.getQname());
            op1.setText(myBean.getOp1());
            op2.setText(myBean.getOp2());
            op3.setText(myBean.getOp3());
            op4.setText(myBean.getOp4());

            return view;
        }
    }

活动文件

package com.patel.ravin.com.domparsing;

    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.ArrayAdapter;
    import android.widget.ListView;
    import android.widget.Spinner;
    import android.widget.TextView;
    import android.widget.Toast;

    import com.patel.ravin.com.domparsing.AsyncTask.AsyncTaskLoader;
    import com.patel.ravin.com.domparsing.AsyncTask.OnAsyncResult;

    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

    import java.util.ArrayList;
    import java.util.HashMap;

    public class MainActivity extends AppCompatActivity {

        TextView textView;
        ListView listView1;
        Adpt adpt;

         ArrayList<MyBean>  arrayList=null;

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

           // textView= (TextView) findViewById(R.id.tv1);
            listView1=(ListView)findViewById(R.id.llv);

    //        Adpt adpt=new Adpt(getApplicationContext(),arrayList);


            //listView.setAdapter(new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,arrayList));
            OnAsyncResult onAsyncResult=new OnAsyncResult() {
                @Override
                public void onAsyncResult(String result) {

                    Log.e("h", result.toString());

                    try {
                      //  textView.setText(""+result.toString());
                     //   String co=result.toString();

                        JSONArray jsonArray=new JSONArray(result);
                        MyBean myBean;
                        arrayList = new ArrayList<>();

                        for(int i=1;i<=jsonArray.length();i++)
                        {
                            JSONObject jsonObject=jsonArray.getJSONObject(i);


                            myBean = new MyBean();
                            myBean.setQid(jsonObject.getString("que"));
                            myBean.setQname(jsonObject.getString("ans"));

                            myBean.setOp1(jsonObject.getString("a"));
                            myBean.setOp2(jsonObject.getString("b"));
                            myBean.setOp3(jsonObject.getString("c"));
                            myBean.setOp4(jsonObject.getString("d"));

                            arrayList.add(myBean);
                            listView1.setAdapter(new Adpt(getApplicationContext(),arrayList));
                        }
                        //JSONObject   object = new JSONObject(result);

                        //String contact = object.getString("que");



                      //  textView.setText(co);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                }
            };

            AsyncTaskLoader asyncTaskLoader=new AsyncTaskLoader(MainActivity.this,onAsyncResult,null,"http://quiz/jsonapi.php");
            asyncTaskLoader.execute();


        }


    }

在自定义列表视图中滚动时取消选择单选按钮 我已经制作了添加的自定义列表视图 自动添加运行时单选按钮 但它在滚动时取消选择

【问题讨论】:

  • 保持单选按钮布尔值......

标签: android listview


【解决方案1】:

这是在 Android 中使用 Listviews 和单选按钮时非常常见的问题。

首先,我建议您查看此帖子: Using radio button in custom listview in Android

现在,我将告诉您哪种解决方案适合我。就我而言,我使用 GridView,但它也适用于 ListView。

在您的适配器类中,您必须为所选项目及其索引提供一个变量,它可能类似于:

private int mSelectedPosition = -1;
private RadioButton mSelectedRB;

然后,定义一个函数来检索此信息:

public int getItemSelected(){
    return  mSelectedPosition;
}

现在,为了使其正常工作,您必须使用 ViewHolder(在我的情况下,GridView 中的每个项目都有一个 Image 和一个 RadioButton),因此您在适配器的类也是如此:

private class ViewHolder {
    ImageView image;
    RadioButton radio;
}

然后,在您的getView 函数中,您必须使用 ViewHolder。在代码中我写了 cmets 来跟随。

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    View view = convertView; // assign the view 
    ViewHolder holder; // declare the ViewHolder

    if(view == null){
        // cutom layout for each row (item) of the ListView
        view = mLayoutInflater.inflate(R.layout.item_list_company, parent, false);
        holder = new ViewHolder();

        // initialize the ViewHolder's field
        holder.image = (ImageView) view.findViewById(R.id.c1);
        holder.radio = (RadioButton)view.findViewById(R.id.cN1);

        view.setTag(holder); // set the tag
    }else{ // already initialized
        holder = (ViewHolder)view.getTag(); // so we only set the tag
    }

    // on click triggered for each RadioButton in the ListView
    holder.radio.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            if(position != mSelectedPosition && mSelectedRB != null){
                mSelectedRB.setChecked(false); // uncheck the last one
            }

            mSelectedPosition = position; // change the item selected index 
            mSelectedRB = (RadioButton)v; // assign the new item selected
        }
    });

    // just to control the right item checked
    if(mSelectedPosition != position){
        holder.radio.setChecked(false);
    }else{
        holder.radio.setChecked(true);
        if(mSelectedRB != null && holder.radio != mSelectedRB){
            mSelectedRB = holder.radio;
        }
    }

    return view;
}

最后,在 ListView 中每个项目的自定义布局(item_list_company.xml 在我的例子中)中,我有以下代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:orientation="vertical"
   android:layout_height="match_parent">
   <ImageView android:id="@+id/c1"
       android:layout_width="wrap_content"
       android:layout_height="100dp"
       android:layout_gravity="center"
       android:scaleType="centerInside" />
   <RadioButton
       android:id="@+id/cN1"
       android:layout_width="wrap_content"
       android:layout_height="50dp"
       android:buttonTint="@color/colorPrimary"
       android:textColor="@color/colorAccent"
       android:focusable="false"
       android:layout_gravity="left"
       android:clickable="false"
       android:focusableInTouchMode="false"
       android:textSize="20dp"/>
</LinearLayout>

特别注意RadioButton的这三个属性:

android:focusable="false"
android:clickable="false"
android:focusableInTouchMode="false"

因此,有了这一切,您只需在 Activity 中设置适配器和 ListView 并调用正确的函数来检索所选项目:

ArrayList<MyBean> arrayList = new ArrayList<>();
ListView listView1 = (ListView)findViewById(R.id.llv);
Adpt adpt = new Adpt(getApplicationContext(), arrayList);

// add data to the ArrayList

adpt.notifyDataSetChanged(); // notify for the new data in the ArrayList

// retrieve the item selected
int selected = adpt.getItemSelected();

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-14
    • 2019-02-16
    • 2016-06-17
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    • 1970-01-01
    • 2018-07-15
    相关资源
    最近更新 更多