将Parcelable与按钮

时间:2017-11-09 14:13:54

标签: java android button parcelable

我正在编写一个简单的应用程序,在这个应用程序中,您可以初始化我的自定义类的实例" Player"然后通过parcelable将这些对象传递给下一个活动。到目前为止这工作正常,但我完全重写了按钮的代码(之前我使用了不同的方法)。现在,如果我没有声明Player实例最终,我会收到错误。当我将鼠标悬停在"播放器1"例如,这一行:

bundle.putParcelable("EXTRA_PLAYER_1", player1);

它说"变量'玩家1'从内部类中访问,需要声明最终"。 这是" onCreate"的相关部分。方法:

etPlayer4 = (EditText) findViewById(R.id.etPlayer4);
String namePlayer4 = etPlayer4.getText().toString();
Player player4 = new Player();
player4.setPlayerName(namePlayer4);
player4.setPlayerScore(0);

btnStartGame = (Button) findViewById(R.id.btnStartGame);
btnStartGame.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent=new Intent(CreatePlayersScreen.this,ScoreScreen.class);
        Bundle bundle = new Bundle();
        bundle.putParcelable("EXTRA_PLAYER_1", player1);
        bundle.putParcelable("EXTRA_PLAYER_2", player2);
        bundle.putParcelable("EXTRA_PLAYER_3", player3);
        bundle.putParcelable("EXTRA_PLAYER_4", player4);
        intent.putExtras(bundle);
        startActivity(intent);
    }
});

如何避免声明Player实例最终?谢谢!

1 个答案:

答案 0 :(得分:0)

在onCreate之外定义你的玩家对象,这样你就可以在课堂的任何地方使用它们。您仍然可以在oncreate

中为它们分配值
// define
Player player4 , player3,
        player2, player1;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    etPlayer4 = (EditText) findViewById(R.id.etPlayer4);
    String namePlayer4 = etPlayer4.getText().toString();

    // assign
    player4 = new Player();
    player4.setPlayerName(namePlayer4);
    player4.setPlayerScore(0);

    btnStartGame = (Button) findViewById(R.id.btnStartGame);
    btnStartGame.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent=new Intent(CreatePlayersScreen.this,ScoreScreen.class);
            Bundle bundle = new Bundle();
            bundle.putParcelable("EXTRA_PLAYER_1", player1);
            bundle.putParcelable("EXTRA_PLAYER_2", player2);
            bundle.putParcelable("EXTRA_PLAYER_3", player3);
            bundle.putParcelable("EXTRA_PLAYER_4", player4);
            intent.putExtras(bundle);
            startActivity(intent);
        }
    });
}