在“自定义列表视图”中反复选择单选按钮

时间:2018-09-11 20:43:33

标签: android listview radio-button

我正在为测验创建一个应用程序。我用单选按钮填充了列表视图,但是在
上  单击任何单选按钮,接下来的第四行中的同一按钮将自动选择。

这是我的代码 MainActivity.java

public class MainActivity extends AppCompatActivity {

String ques_pdf;
PDFView pdfView;
String url = "api.abc.com"
private List<VideoListDataItem> dataFeed= new ArrayList<VideoListDataItem>();
ListView listView;
String test_id,marked_answer;
String q_no;
@Nullable
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    pdfView = (PDFView)findViewById(R.id.question_pdf);
    final ArrayAdapter<VideoListDataItem> adapter = new MainActivity.Adapter();
    listView = findViewById(R.id.listview_answers);


    RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
            url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        JSONArray temp = response.getJSONArray("mock_test_pt");

                        for (int i = 0; i < temp.length(); i++) {
                            JSONObject buffer = temp.getJSONObject(i);
                            String marks_correct_ans= buffer.getString("marks_correct_ans");
                            String negative_mark= buffer.getString("negative_mark");
                            String duration = buffer.getString("duration");
                            ques_pdf = buffer.getString("ques_pdf");
                            String total_question = buffer.getString("total_question");
                            test_id = buffer.getString("id");
                            Log.i(" Test id",buffer.getString("id"));

                            int total_questions = Integer.parseInt(total_question);

                            for (int j=1;j<=total_questions;j++) {
                                dataFeed.add(new VideoListDataItem("" + j, "", "", "", "", ""));
                                adapter.notifyDataSetChanged();

                            }
                            new RetrievePDF().execute(ques_pdf);
                            Log.i("ques_pdf",ques_pdf);


                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
    jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    queue.add(jsonObjectRequest);

    Log.i("Test paper","After loading pdf");
    JsonObjectRequest jsonObjectRequest2 = new JsonObjectRequest(Request.Method.GET,
            url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        Log.i("Answer", "" + response.toString());
                        JSONArray temp = response.getJSONArray("subject_wise_test_ans");


                        for (int i = 0; i < temp.length(); i++) {
                            JSONObject buffer = temp.getJSONObject(i);
                            JSONObject answer = buffer.getJSONObject("answer");

                            String id= buffer.getString("id");
                            String test_id1= buffer.getString("test_id");
                            Log.i("Test Id in answer",test_id1);
                            String subject_name = buffer.getString("subject_name");
                            String marks_pluse = buffer.getString("marks_pluse");
                            String marks_minus = buffer.getString("marks_minus");
                            String answer_set = buffer.getString("answer");
                            q_no = buffer.getString("question_no");
                            String temp_string;
                            temp_string=test_id;
                            Log.i("Answer API",answer.toString());

                            if (test_id1.equals(test_id) ) {
                               // Toast.makeText(getApplicationContext(), "Matched!!!", Toast.LENGTH_SHORT).show();
                                break;

                            }
                        }
                        Log.i("QID",test_id);


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
    jsonObjectRequest2.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    queue.add(jsonObjectRequest2);


    listView.setAdapter( adapter);





}

private class Adapter extends ArrayAdapter<VideoListDataItem> {

    public Adapter() {
        super(MainActivity.this, R.layout.sample_answer_fragment,dataFeed);
    }


    @NonNull
    @Override
    public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {

        if (convertView == null)
        {
            convertView = getLayoutInflater().inflate(R.layout.sample_answer_fragment,null,false);
        }

        VideoListDataItem currentItem = dataFeed.get(position);
        final RadioGroup radioGroup = (RadioGroup)convertView.findViewById(R.id.radiogroup);

        ImageView removeAnswer = (ImageView)convertView.findViewById(R.id.del_option);
        removeAnswer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                radioGroup.clearCheck();
            }
        });
        final TextView question_no = (TextView) convertView.findViewById(R.id.serial_option);
        final RadioButton radioButtonA = (RadioButton)convertView.findViewById(R.id.optionA) ;
        final RadioButton radioButtonB = (RadioButton)convertView.findViewById(R.id.optionB) ;
        final RadioButton radioButtonC = (RadioButton)convertView.findViewById(R.id.optionC) ;
        final RadioButton radioButtonD = (RadioButton)convertView.findViewById(R.id.optionD) ;
        final RadioButton[] radioButton = new RadioButton[1];
        final int[] selectedId = new int[1];
        final View finalConvertView = convertView;
        question_no.setText(currentItem.getId());
        // radioButtonA.setTag(position);


        radioButtonA.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                marked_answer = radioButtonA.getText().toString();
                Toast.makeText(getApplicationContext(), question_no.getText().toString()+" "+marked_answer+" "+position, Toast.LENGTH_SHORT).show();
                //  databaseHelper.saveAnswer(question_no.getText().toString(),test_id,marked_answer);
            }
        });
        radioButtonB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                marked_answer = radioButtonB.getText().toString();
                Toast.makeText(getApplicationContext(), question_no.getText().toString()+" "+marked_answer+" "+position, Toast.LENGTH_SHORT).show();
                //  databaseHelper.saveAnswer(question_no.getText().toString(),test_id,marked_answer);

            }
        });
        radioButtonC.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                marked_answer = radioButtonC.getText().toString();
                Toast.makeText(getApplicationContext(), question_no.getText().toString()+" "+marked_answer+" "+position, Toast.LENGTH_SHORT).show();

                //databaseHelper.saveAnswer(question_no.getText().toString(),test_id,marked_answer);

            }
        });
        radioButtonD.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                marked_answer = radioButtonA.getText().toString();
                Toast.makeText(getApplicationContext(), question_no.getText().toString()+" "+marked_answer+" "+position, Toast.LENGTH_SHORT).show();
                //

            }
        });
        //    final RadioButton[] radioButton = new RadioButton[1];

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                Toast.makeText(getApplicationContext(),question_no.getText().toString() , Toast.LENGTH_SHORT).show();
                //

            }
        });


        return convertView;
    }

}


class RetrievePDF extends AsyncTask<String,Void,InputStream>
{

    @Override
    protected InputStream doInBackground(String... strings) {
        InputStream inputStream=null;
        try{
            URL url = new URL(strings[0]);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            if (httpURLConnection.getResponseCode()==200)
            {
                inputStream = new BufferedInputStream(httpURLConnection.getInputStream());

            }


        }
        catch (Exception e){
            Log.i("PDF Async Exception",e.toString());
        }
        return inputStream;
    }

    @Override
    protected void onPostExecute(InputStream inputStream) {
        pdfView.fromStream(inputStream).load();

    }
}
} 

sample_answer_fragment.xml的代码

<?xml version="1.0" encoding="utf-8"?>

    <LinearLayout 
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="horizontal" android:layout_width="match_parent"
  android:layout_height="match_parent">


<TextView

    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/serial_option"
    android:text="1"
    android:layout_margin="10dp"/>


   <RadioGroup
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:orientation="horizontal"
  android:id="@+id/radiogroup">



    <RadioButton
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="A"
  android:id="@+id/optionA"
  android:layout_margin="10dp"/>

<RadioButton

    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="B"
    android:id="@+id/optionB"
    android:layout_margin="10dp"/>
<RadioButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="C"
    android:id="@+id/optionC"
    android:layout_margin="10dp"/>
<RadioButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="D"
    android:id="@+id/optionD"
    android:layout_margin="10dp"/>

<ImageView
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:layout_marginRight="10dp"
    android:layout_marginTop="10dp"
    android:src="@drawable/ic_launcher_background"
    android:id="@+id/del_option"
    android:textAlignment="viewEnd"
    android:gravity="end" />
    </RadioGroup>

    </LinearLayout>

除单选按钮外,此代码中的所有内容均正常运行。自动选择不同行的单选按钮

1 个答案:

答案 0 :(得分:1)

复制此...我已修改您的适配器类

 private class Adapter extends ArrayAdapter<VideoListDataItem> {

    public Adapter() {
        super(MainActivity.this, R.layout.sample_answer_fragment,dataFeed);
    }


    @NonNull
    @Override
    public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        final ViewHolder viewholder;

        if (convertView == null)
        {
            convertView = getLayoutInflater().inflate(R.layout.sample_answer_fragment,null,false);
            viewholder = new ViewHolder();

            viewholder.radioGroup = (RadioGroup)convertView.findViewById(R.id.radiogroup);

            viewholder.removeAnswer = (ImageView)convertView.findViewById(R.id.del_option);

            viewholder.question_no = (TextView) convertView.findViewById(R.id.serial_option);

            viewholder.radioButtonA = (RadioButton)convertView.findViewById(R.id.optionA) ;
            viewholder.radioButtonB = (RadioButton)convertView.findViewById(R.id.optionB) ;
            viewholder.radioButtonC = (RadioButton)convertView.findViewById(R.id.optionC) ;
            viewholder.radioButtonD = (RadioButton)convertView.findViewById(R.id.optionD) ;

            convertView.setTag(viewholder);

        }else{

            viewholder=(ViewHolder) convertView.getTag();

        }

        VideoListDataItem currentItem = dataFeed.get(position);
        viewholder.removeAnswer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewholder.radioGroup.clearCheck();
            }
        });

        final RadioButton[] radioButton = new RadioButton[1];
        final int[] selectedId = new int[1];
        final View finalConvertView = convertView;
        question_no.setText(currentItem.getId());
        // radioButtonA.setTag(position);


        viewholder.radioButtonA.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                marked_answer = radioButtonA.getText().toString();
                Toast.makeText(getApplicationContext(), question_no.getText().toString()+" "+marked_answer+" "+position, Toast.LENGTH_SHORT).show();
                //  databaseHelper.saveAnswer(question_no.getText().toString(),test_id,marked_answer);
            }
        });
        viewholder.radioButtonB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                marked_answer = radioButtonB.getText().toString();
                Toast.makeText(getApplicationContext(), question_no.getText().toString()+" "+marked_answer+" "+position, Toast.LENGTH_SHORT).show();
                //  databaseHelper.saveAnswer(question_no.getText().toString(),test_id,marked_answer);

            }
        });
        viewholder.radioButtonC.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                marked_answer = radioButtonC.getText().toString();
                Toast.makeText(getApplicationContext(), question_no.getText().toString()+" "+marked_answer+" "+position, Toast.LENGTH_SHORT).show();

                //databaseHelper.saveAnswer(question_no.getText().toString(),test_id,marked_answer);

            }
        });
        viewholder.radioButtonD.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                marked_answer = radioButtonA.getText().toString();
                Toast.makeText(getApplicationContext(), question_no.getText().toString()+" "+marked_answer+" "+position, Toast.LENGTH_SHORT).show();
                //

            }
        });
        //    final RadioButton[] radioButton = new RadioButton[1];

        viewholder.radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                Toast.makeText(getApplicationContext(),question_no.getText().toString() , Toast.LENGTH_SHORT).show();
                //

            }
        });


        return convertView;
    }

    private class ViewHolder{
    RadioGroup radioGroup;
    ImageView removeAnswer;
    TextView question_no;
    RadioButton radioButtonA,radioButtonB,radioButtonC,radioButtonD;
    }

   }

希望这会对您有所帮助。