在类中使用findViewById的问题

时间:2016-08-18 13:02:27

标签: java android android-layout

我正在尝试创建一个类来重复使用以单选按钮形式提供多项选择的评论/测验。

使用以下功能,我对单个活动没有任何问题

public void onClickListenerButton(){
    radioGroupReview = (RadioGroup)  findViewById(R.id.radioGroupReview);
    btnReviewSubmit = (Button) findViewById(R.id.btnReviewSubmit);

    btnReviewSubmit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int selection = radioGroupReview.getCheckedRadioButtonId();
            radio_button = (RadioButton) findViewById(selection);

            if(selection==R.id.radioCorrectAnswer) {
                textrReviewResult.setText("Correct!");
                btnReviewContinue.setVisibility(View.VISIBLE);
                btnReviewSubmit.setVisibility(View.GONE);

            } else {
                textReviewResult.setText("Try Again.");

            }

        }
    });

}

将它应用于类已经证明是困难的,因为我不确定如何替换findViewById(选择)因此抛弃下面的If / Else逻辑。

public class ReviewLogic {

    public void onClickListenerButton(final Button btnSubmit, final Button btnContinue, final RadioGroup radioGroup,final RadioButton radioButton, final TextView result){

        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int selection = radioGroup.getCheckedRadioButtonId();
                radioButton = (RadioButton) findViewById(selection);

                if(selection==R.id.radioCorrectAnswer) {
                    result.setText("Correct!");
                    btnContinue.setVisibility(View.VISIBLE);
                    btnSubmit.setVisibility(View.GONE);
                } else {
                    result.setText("Try Again.");
                }

            }
        });

    }
}

我可以考虑采用哪些替换来使逻辑仍然有效但排除findViewById?

谢谢

2 个答案:

答案 0 :(得分:1)

您可以尝试在radioGroup之前添加findViewById,这样您就会有以下内容:

radioButton = (RadioButton) radioGroup.findViewById(selection);

答案 1 :(得分:0)

您必须将活动对象传递给onClickListenerButton功能

访问radioButton by

radioButton = (RadioButton)activity.findViewById(selection);