radiogroup.setOnCheckedListener未按预期工作。(更改单选按钮的颜色)

时间:2015-06-11 07:13:27

标签: java android listview baseadapter

我有一个活动,其中有一个问题和答案部分,在一个广播组中有4个选项的问题。在选择答案时,必须将答案的背景更改为绿色或红色(基于正确或错误)。

我有一个调用BaseAdapter类的活动,该类监听setOnCheckedListener。

PreviewAdapter.java

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

    import org.apache.http.NameValuePair;
    import org.apache.http.message.BasicNameValuePair;

    import android.content.Context;
    import android.graphics.Color;
    import android.support.design.widget.Snackbar;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.Button;
    import android.widget.CheckBox;
    import android.widget.EditText;
    import android.widget.LinearLayout;
    import android.widget.RadioButton;
    import android.widget.RadioGroup;
    import android.widget.TextView;
    import android.widget.RadioGroup.OnCheckedChangeListener;
    import android.widget.Toast;

    import technibits.com.pme.R;
    import technibits.com.pme.activity.AsyncTaskCall;
    import technibits.com.pme.activity.MasterDownload;
    import technibits.com.pme.activity.PreviewActivity;
    import technibits.com.pme.activity.ReviewFragment;
    import technibits.com.pme.data.Quizdata;
    import technibits.com.pme.data.ResultData;


    public class PreviewAdapter extends BaseAdapter {
        private Context context;
        ReviewFragment activity;

        Quizdata data;
        String formID;
        EditText dateText;
        public ViewHolderA viewHolder;
        int queNo;
        int size;
        String select;
        public ResultData resData;
        String urlMark = "xx.com/mark-for-review.php";
        String urlRemove = "xx.com/mark-for-review-delete.php";
        public RadioButton rButton = null;
        HashMap<String, String> editTextvalue = new HashMap<String, String>();
        MasterDownload httpRequest;
        public String ansOption;
        PreviewActivity previewActivity;

        public PreviewAdapter(Context conte, Quizdata form, int qNO, int device, String strSelect ) {
            super();
            context = conte;
            data = form;
            queNo = qNO + 1;
            size = device;
            select = strSelect;
    //        previewActivity=pv;
        }

        @Override
        public int getCount() {

            return 3;
        }

        @Override
        public Object getItem(int position) {

            return null;
        }

        @Override
        public long getItemId(int position) {

            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
             View row = convertView;
            LayoutInflater mInflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            if (size == 7) {
                row = mInflater.inflate(R.layout.quiz_layout_seven, parent, false);
            } else {
                row = mInflater.inflate(R.layout.quiz_layout, parent, false);
            }
            if (row != null) {

                viewHolder = new ViewHolderA();

                viewHolder.reviewLayout = (LinearLayout) row.findViewById(R.id.review);

                viewHolder.questionLayout = (LinearLayout) row.findViewById(R.id.question);

                viewHolder.answerLayout = (LinearLayout) row.findViewById(R.id.answer);

                viewHolder.questionView = (TextView) viewHolder.questionLayout.findViewById(R.id.questionView);

                viewHolder.textQno = (TextView) row.findViewById(R.id.qNo);

                viewHolder.radioGroup = (RadioGroup) row.findViewById(R.id.radioGroup);

                viewHolder.rButton1 = (RadioButton) row.findViewById(R.id.RadioButton01);
                viewHolder.rButton2 = (RadioButton) row.findViewById(R.id.RadioButton02);
                viewHolder.rButton3 = (RadioButton) row.findViewById(R.id.RadioButton03);
                viewHolder.rButton4 = (RadioButton) row.findViewById(R.id.RadioButton04);

                viewHolder.reviewBox = (CheckBox) row.findViewById(R.id.rCheckBox);

                viewHolder.showReview = (Button) row.findViewById(R.id.showReview);
    //            viewHolder.infoButton = (Button) row.findViewById(R.id.info);

            } else {
                viewHolder = (ViewHolderA) row.getTag();
            }


            if (position == 0) {
                viewHolder.reviewLayout.setVisibility(View.VISIBLE);
                viewHolder.questionLayout.setVisibility(View.GONE);
                viewHolder.answerLayout.setVisibility(View.GONE);
                int check = data.getISchecked();
                if (check == 1) {
                    viewHolder.reviewBox.setChecked(true);
                } else {
                    viewHolder.reviewBox.setChecked(false);
                }

    //                  String review = data.getStatus();
    //                  if (review != null) {
    //                      if (review.equals("A")) {
                viewHolder.reviewBox.setEnabled(false);
    //                      }
    //                  }
                if (select != null) {
                    viewHolder.reviewLayout.setVisibility(View.GONE);
                }

            } else if (position == 1) {
                viewHolder.questionLayout.setVisibility(View.VISIBLE);
                viewHolder.reviewLayout.setVisibility(View.GONE);
                viewHolder.answerLayout.setVisibility(View.GONE);
                viewHolder.questionView.setText(data.getQuestion());
                viewHolder.textQno.setText("Q." + String.valueOf(queNo));
            } else if (position == 2) {
                viewHolder.answerLayout.setVisibility(View.VISIBLE);
                viewHolder.questionLayout.setVisibility(View.GONE);
                viewHolder.reviewLayout.setVisibility(View.GONE);
                viewHolder.radioGroup.setEnabled(true);
                viewHolder.rButton1.setText(data.getOptionA());
                viewHolder.rButton2.setText(data.getOptionB());
                viewHolder.rButton3.setText(data.getOptionC());
                viewHolder.rButton4.setText(data.getOptionD());

                final View uiview = row;
    //            viewHolder.rButton1.setBackgroundColor(Color.YELLOW);-------> Here color changes occur

            if (select != null) {
                viewHolder.radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(RadioGroup group, int checkedId) {

                        ansOption = "yes";
                        data.setIsAnswer(1);
                        int answer = Integer.valueOf(data.getAnswer());
                        int selected = -1;

                        if (checkedId == R.id.RadioButton01) {
                            selected = 1;
                            rButton = viewHolder.rButton1;
                            viewHolder.rButton1.setBackgroundColor(Color.YELLOW);

                        } else if (checkedId == R.id.RadioButton02) {
                            selected = 2;
                            rButton = viewHolder.rButton2;
                        } else if (checkedId == R.id.RadioButton03) {
                            selected = 3;
                            rButton = viewHolder.rButton3;
                        } else if (checkedId == R.id.RadioButton04) {
                            selected = 4;
                            rButton = viewHolder.rButton4;
                        }
                        if (rButton != null) {
                            if (answer + 1 == selected) {
                                rButton.setBackgroundColor(Color.GREEN);-------> Here color changes is not working
                                String dd = rButton.getText().toString();
                                rButton.setText("Correct answer");
                            } else {

                                rButton.setBackgroundColor(Color.RED);
                                data.setWrongAnswer(selected);
                                String dd = rButton.getText().toString();
                                System.out.println(dd);
                            }
                        }

                        if (answer == 0) {
                            viewHolder.rButton1.setBackgroundColor(Color.GREEN);
                        } else if (answer == 1) {
                            viewHolder.rButton2.setBackgroundColor(Color.GREEN);
                        } else if (answer == 2) {
                            viewHolder.rButton3.setBackgroundColor(Color.GREEN);
                        } else if (answer == 3) {
                            viewHolder.rButton4.setBackgroundColor(Color.GREEN);
                        }

                            for (int i = 0; i < viewHolder.radioGroup.getChildCount(); i++) {
                                viewHolder.radioGroup.getChildAt(i).setEnabled(false);
                            }
                        List<NameValuePair> params = new ArrayList<NameValuePair>();
                        params.add(new BasicNameValuePair("userid", "android@gmail.com"));
                        params.add(new BasicNameValuePair("qid", data.getQuestionID()));
                        AsyncTaskCall ask = new AsyncTaskCall(context, "review", params);
                        ask.execute(urlRemove);
                    }
                });
            } else {
                System.out.println("data.getIsAnswer()  " + data.getIsAnswer());
                if (data.getIsAnswer() == 1) {
                    int wrong = data.getWrongAnswer();
                    int selected = -1;

                    if (wrong == 1) {
                        selected = 1;
                        rButton = viewHolder.rButton1;
                        setcolorGreen(viewHolder.rButton1);
                    } else if (wrong == 2) {
                        selected = 2;
                        rButton = viewHolder.rButton2;
                    } else if (wrong == 3) {
                        selected = 3;
                        rButton = viewHolder.rButton3;
                    } else if (wrong == 4) {
                        selected = 4;
                        rButton = viewHolder.rButton4;
                    }

                    int answer = Integer.valueOf(data.getAnswer());
                    if (rButton != null) {
                        if (answer + 1 == selected) {

                            rButton.setBackgroundColor(Color.GREEN);
                        } else {
                            rButton.setBackgroundColor(Color.RED);
                        }
                    }

                    if (answer == 0) {
                        viewHolder.rButton1.setBackgroundColor(Color.GREEN);
                    } else if (answer == 1) {
                        viewHolder.rButton2.setBackgroundColor(Color.GREEN);
                    } else if (answer == 2) {
                        viewHolder.rButton3.setBackgroundColor(Color.GREEN);
                    } else if (answer == 3) {
                        viewHolder.rButton4.setBackgroundColor(Color.GREEN);
                    }


                    for (int i = 0; i < viewHolder.radioGroup.getChildCount(); i++) {
                        viewHolder.radioGroup.getChildAt(i).setEnabled(false);
                    }


                }
            }


        }

        else

        {
            viewHolder.answerLayout.setVisibility(View.GONE);
            viewHolder.questionLayout.setVisibility(View.GONE);
            viewHolder.reviewLayout.setVisibility(View.GONE);
        }

        return row;

    }


        static class ViewHolderA {

            LinearLayout reviewLayout;
            LinearLayout questionLayout;
            LinearLayout answerLayout;

            Button showReview;

            TextView questionView;
            TextView textQno;
            RadioGroup radioGroup;


            public RadioButton rButton1;
            public RadioButton rButton2;
            public RadioButton rButton3;
            public RadioButton rButton4;

            CheckBox reviewBox;

        }
        void setcolorGreen(RadioButton rb){
            rb.setBackgroundColor(Color.GREEN);
            Toast.makeText(context,"Correct",Toast.LENGTH_SHORT).show();
        }
        void setcolorRed(RadioButton rb){
            rb.setBackgroundColor(Color.RED);
            Toast.makeText(context,"Wrong",Toast.LENGTH_SHORT).show();
        }
    }


The class calling this is

PreviewActivity.java



public class PreviewActivity extends Activity {
    int device;
    Button priv;
    Button next;
    boolean pCheck;
    boolean nCheck;
    Quizdata dataSource;
    int count, position;
    String select;
    int iNext = 0;
    ListView list;
    ArrayList<Quizdata> data;
    Context context;
    TestAdapter adapter;

    @SuppressWarnings("unchecked")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;

        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);

        int widthPixels = metrics.widthPixels;
        int heightPixels = metrics.heightPixels;
        float scaleFactor = metrics.density;
        float widthDp = widthPixels / scaleFactor;
        float heightDp = heightPixels / scaleFactor;

        float smallestWidth = Math.min(widthDp, heightDp);
        if (smallestWidth > 720) {
            device = 10;
        } else if (smallestWidth >= 600) {
            device = 7; //Device is a 7" tablet
            setContentView(R.layout.study_mode_seven);
        } else {
            setContentView(R.layout.study_mode);
        }


//       Bundle bundle = getIntent().getExtras();
        list = (ListView) findViewById(R.id.listView1);
        data = (ArrayList<Quizdata>) getIntent().getSerializableExtra("data");

        count = getIntent().getExtras().getInt("count");
        select = getIntent().getExtras().getString("review");
        position = getIntent().getExtras().getInt("question_no");

//       count = data.size();

        if (data.size() > 0) {
            dataSource = data.get(position);
            adapter = new TestAdapter(context, dataSource, iNext, device, select);
//           adapter.resData = resData;
            list.setAdapter(adapter);
        }

        priv = (Button) findViewById(R.id.prev);
        next = (Button) findViewById(R.id.next);
        Button exp = (Button) findViewById(R.id.exp);
        list = (ListView) findViewById(R.id.listView1);
        priv.setEnabled(false);

        if (select != null) {
            priv.setVisibility(View.GONE);
            exp.setVisibility(View.GONE);
            next.setVisibility(View.GONE);
        }

        exp.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                AlertDialog.Builder alert = new AlertDialog.Builder(context);
                alert.setTitle("Explanation");
                alert.setMessage(dataSource.getDescription());


                alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        // Do something with value!
                    }
                });


                alert.show();
            }
        });

        next.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (next.getText().toString().equals("Next")) {
                    priv.setEnabled(true);

                    if (iNext == 0) {
                        iNext = 1;
                        pCheck = true;

                    }
                    if (nCheck) {
                        iNext++;
                    }
                    if (iNext < count) {
                        dataSource = data.get(iNext);
                        PreviewAdapter adapter = new PreviewAdapter(context, dataSource, iNext, device, select);

                        list.setAdapter(adapter);
                        priv.setEnabled(true);
                        iNext++;
                        pCheck = true;
                        nCheck = false;

                    }
                    if (iNext == count) {
//                      next.setEnabled(false);
                        next.setText("Finish");
//                      next.setBackgroundColor(Color.RED);
                        iNext = count - 1;
                        pCheck = false;


                    }

                } else {
                    finish();
                }


            }


        });

        priv.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
                if (iNext == count) {
                    iNext = count - 1;
                }
                if (pCheck) {
                    iNext--;
                }
                if (iNext > 0) {
                    iNext--;
                    dataSource = data.get(iNext);
                    PreviewAdapter adapter = new PreviewAdapter(context, dataSource, iNext, device, select);
//                      adapter.resData = resData;
                    list.setAdapter(adapter);
                    next.setEnabled(true);
                    if (next.getText().toString().equals("Finish")) {
                        next.setText("Next");
//                          next.setBackgroundDrawable(priv.getBackground());
                    }
                    nCheck = true;
                    pCheck = false;

                }
                if (iNext == 0) {
                    priv.setEnabled(false);
                    iNext = 0;
                    nCheck = false;

                }


            }
        });


    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        sendMessage();
    }

    private void sendMessage() {
        Log.d("sender", "Broadcasting message");
        Intent intent = new Intent("custom-event-name");
        // You can also include some extra data.
        intent.putExtra("message", adapter.ansOption);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }

}

上面调用的Activity是

PreviewActivity.java

package technibits.com.pme.activity;

import java.util.ArrayList;

import technibits.com.pme.R;
import technibits.com.pme.adapter.PreviewAdapter;
import technibits.com.pme.adapter.TestAdapter;
import technibits.com.pme.data.Quizdata;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

public class PreviewActivity extends Activity {
    int device;
    Button priv;
    Button next;
    boolean pCheck;
    boolean nCheck;
    Quizdata dataSource;
    int count, position;
    String select;
    int iNext = 0;
    ListView list;
    ArrayList<Quizdata> data;
    Context context;
    TestAdapter adapter;

    @SuppressWarnings("unchecked")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;

        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);

        int widthPixels = metrics.widthPixels;
        int heightPixels = metrics.heightPixels;
        float scaleFactor = metrics.density;
        float widthDp = widthPixels / scaleFactor;
        float heightDp = heightPixels / scaleFactor;

        float smallestWidth = Math.min(widthDp, heightDp);
        if (smallestWidth > 720) {
            device = 10;
        } else if (smallestWidth >= 600) {
            device = 7; //Device is a 7" tablet
            setContentView(R.layout.study_mode_seven);
        } else {
            setContentView(R.layout.study_mode);
        }


//       Bundle bundle = getIntent().getExtras();
        list = (ListView) findViewById(R.id.listView1);
        data = (ArrayList<Quizdata>) getIntent().getSerializableExtra("data");

        count = getIntent().getExtras().getInt("count");
        select = getIntent().getExtras().getString("review");
        position = getIntent().getExtras().getInt("question_no");

//       count = data.size();

        if (data.size() > 0) {
            dataSource = data.get(position);
            adapter = new TestAdapter(context, dataSource, iNext, device, select);
//           adapter.resData = resData;
            list.setAdapter(adapter);
        }

        priv = (Button) findViewById(R.id.prev);
        next = (Button) findViewById(R.id.next);
        Button exp = (Button) findViewById(R.id.exp);
        list = (ListView) findViewById(R.id.listView1);
        priv.setEnabled(false);

        if (select != null) {
            priv.setVisibility(View.GONE);
            exp.setVisibility(View.GONE);
            next.setVisibility(View.GONE);
        }

        exp.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                AlertDialog.Builder alert = new AlertDialog.Builder(context);
                alert.setTitle("Explanation");
                alert.setMessage(dataSource.getDescription());


                alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        // Do something with value!
                    }
                });


                alert.show();
            }
        });

        next.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (next.getText().toString().equals("Next")) {
                    priv.setEnabled(true);

                    if (iNext == 0) {
                        iNext = 1;
                        pCheck = true;

                    }
                    if (nCheck) {
                        iNext++;
                    }
                    if (iNext < count) {
                        dataSource = data.get(iNext);
                        PreviewAdapter adapter = new PreviewAdapter(context, dataSource, iNext, device, select);

                        list.setAdapter(adapter);
                        priv.setEnabled(true);
                        iNext++;
                        pCheck = true;
                        nCheck = false;

                    }
                    if (iNext == count) {
//                      next.setEnabled(false);
                        next.setText("Finish");
//                      next.setBackgroundColor(Color.RED);
                        iNext = count - 1;
                        pCheck = false;


                    }

                } else {
                    finish();
                }


            }


        });

        priv.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
                if (iNext == count) {
                    iNext = count - 1;
                }
                if (pCheck) {
                    iNext--;
                }
                if (iNext > 0) {
                    iNext--;
                    dataSource = data.get(iNext);
                    PreviewAdapter adapter = new PreviewAdapter(context, dataSource, iNext, device, select);
//                      adapter.resData = resData;
                    list.setAdapter(adapter);
                    next.setEnabled(true);
                    if (next.getText().toString().equals("Finish")) {
                        next.setText("Next");
//                          next.setBackgroundDrawable(priv.getBackground());
                    }
                    nCheck = true;
                    pCheck = false;

                }
                if (iNext == 0) {
                    priv.setEnabled(false);
                    iNext = 0;
                    nCheck = false;

                }


            }
        });


    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        sendMessage();
    }

    private void sendMessage() {
        Log.d("sender", "Broadcasting message");
        Intent intent = new Intent("custom-event-name");
        // You can also include some extra data.
        intent.putExtra("message", adapter.ansOption);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }

}

当我调试Adapter类时,它完全符合app的逻辑。但颜色本身并没有改变。

可能出现的问题是什么?

1 个答案:

答案 0 :(得分:0)

视图(行)在侦听器中没有范围。所以我声明了最终视图(uiview)的视图,它确实在onChecklistener中有作用域。之后它很酷。但我仍然不知道不使用上一种方法的原因。