0

我试图从下面的 Button onClick 方法中获取字符串firstChoicesecondChoice的值,并在同一个类中使用它。问题是我知道您不能从 void 方法返回字符串值。请看一下我下面的内容:

 public class Question extends Activity implements OnClickListener{

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_question);

        Choice1 = (Button) findViewById(R.id.Choice4);
        Choice1.setOnClickListener(Question.this);

        Choice2 = (Button) findViewById(R.id.Choice5);
        Choice2.setOnClickListener(Question.this);

        firstChoice;
        secondChoice;

    public void onClick(View view) {
            switch(view.getId()) {
              case R.id.Choice4:
                  showSelectPicksDialog();
                  Button b = (Button)view;
                String firstChoice = b.getText().toString();

                break;

              case R.id.Choice5:
                  showSelectPicksDialog2();
                  Button v = (Button)view;
                String secondChoice = v.getText().toString();// 
                break;

              default:
                break;
            }
          }

有没有办法获得这些值?就像现在一样,当我尝试在我的 on Create 方法中调用值时,我收到错误消息,指出 firstChoice 和 secondChoice “无法解析为类型”。

4

1 回答 1

0

有很多方法,您可以使用类变量,例如:

public class Question extends Activity implements OnClickListener{
    String firstChoice;    
    String secondChoice;    
    Button choice1;
    Button choice2;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_question);

        choice1 = (Button) findViewById(R.id.Choice4);
        choice1.setOnClickListener(Question.this);

        choice2 = (Button) findViewById(R.id.Choice5);
        choice2.setOnClickListener(Question.this);

        public void onClick(View view) {
            switch(view.getId()) {
            case R.id.Choice4:
                showSelectPicksDialog();
                Button b = (Button)view;
                firstChoice = b.getText().toString();
                break;

            case R.id.Choice5:
                showSelectPicksDialog2();
                Button v = (Button)view;
                secondChoice = v.getText().toString();
                break;

            default:
                break;
            }
        }
    }
}
于 2012-10-22T22:30:17.830 回答