单击(按钮)三

时间:2017-08-24 10:30:35

标签: java android android-intent android-edittext textview

我正在尝试将int用户输入传递给下一个类并打印它,看它在继续使用它之前是否有效。

Home.java

开始和退出按钮

public class Home extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button one = (Button) findViewById(R.id.b1);
        one.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToSecondActivity();
            }
        });
        Button two = (Button) findViewById(R.id.b2);
        two.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
    private void goToSecondActivity() {
        Intent i = new Intent(this, SelectNumberOfPlayers.class);
        startActivity(i);
    }
}

SelectNumberOfPlayers.java

仅输入输入中的数字并将其传递给StartGame.class

public class SelectNumberOfPlayers extends AppCompatActivity {

    EditText numberOfPlayers;
    Button three;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.enter_number_of_players);
        three = (Button) findViewById(R.id.button3);
        three.setOnClickListener(new View.OnClickListener(){

            public void onClick(View v){

                String txt = numberOfPlayers.getText().toString();
                Intent i = new Intent(getApplicationContext(), StartGame.class);
                i.putExtra("players", txt);
                startActivity(i);
            }
        });
    }
}

StartGame.java

接收Int并打印到TextView

public class StartGame extends AppCompatActivity {

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

        Intent i = getIntent();

        TextView numOfPlayersVal = (TextView) findViewById(R.id.txt2);
        numOfPlayersVal.setText(i.getStringExtra("Player number"));
    }
}

错误发生在哪里?我已将输入键盘设置为仅采用数字

1 个答案:

答案 0 :(得分:0)

<强> 1。你忘记初始化你的editext首先在你的SelectNumberOfPlayers活动中初始化

numberOfPlayers = (EditText) findViewById(R.id.numberOfPlayers);

<强> 2。   密钥必须相同才能通过意图传递和接收数据

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

    Intent i = getIntent();

    TextView numOfPlayersVal = (TextView) findViewById(R.id.txt2);
    numOfPlayersVal.setText(i.getStringExtra("players"));
}