首页 > 解决方案 > 当我把它放在 try 块中时按钮不起作用

问题描述

我正在开发一个应用程序,我进入了这个:

第一活动:

EditText inputCorrect = findViewById(R.id.inputCorrect);
Button calcButton = findViewById(R.id.calculateButton);

try {
    int correctAmount = Integer.parseInt(inputCorrect.getText().toString());
    Intent resultPage = new Intent(getApplicationContext(),resultActivity.class);
    resultPage.putExtra("c_a",correctAmount);
    calcButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(resultPage);
        }
    });
} catch (NumberFormatException nfe) {
}

第二活动:

Bundle myIntent = getIntent().getExtras();
int value =myIntent.getInt("c_a");

我想通过这些活动传递一个 int,但是当我按下按钮时它不起作用。

如果我将按钮无效try{ },它不会检测到resultPage

有任何想法吗?太感谢了。

标签: javaandroid

解决方案


试试这个代码,它对我有用。

public class TestButtonNotWork extends AppCompatActivity {

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

        EditText inputCorrect = findViewById(R.id.inputCorrect);
        Button calcButton = findViewById(R.id.calculateButton);
        Log.d("TestButtonNotWork", "TANCOLO===> init views ");

        calcButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    int correctAmount = Integer.parseInt(inputCorrect.getText().toString());
                    Log.d("TestButtonNotWork", "TANCOLO===> init views, correctAmount = " + correctAmount);

                    Intent resultPage = new Intent(getApplicationContext(), ResultActivity.class);
                    resultPage.putExtra("c_a", correctAmount);

                    Log.d("TestButtonNotWork", "TANCOLO===> start ResultActivity");
                    startActivity(resultPage);

                } catch (Exception exception) {
                    Log.d("TestButtonNotWork", "TANCOLO===> exception = " + exception);
                }
            }
        });
    }
}

注意: Integer.parseInt()必须使用try .. catch,否则会崩溃


推荐阅读