gpt4 book ai didi

java - 为什么我的值没有在 Android Studio 中使用 startActivityForResult() 在 Activity 之间传递?

转载 作者:行者123 更新时间:2023-12-02 09:17:39 24 4
gpt4 key购买 nike

我有两个按钮,单击它们时,我想将 1 或 2 传递给第二个 Activity 。我使用了intent.putExtra和intent.getExtra,但是当我检查第二个 Activity 中的变量值时,它始终为0。

主要 Activity

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

oneDownButton = (Button) findViewById(R.id.oneDownButton);
twoDownButton = (Button) findViewById(R.id.twoDownButton);
oneDownButton.setOnClickListener(this);
twoDownButton.setOnClickListener(this);
}
@Override
public void onClick(View v)
{
Intent intent = new Intent(this, TheCode.class);


switch (v.getId())
{
case R.id.oneDownButton:
intent.putExtra("TAKE_DOWN_NUMBER", 1);
startActivityForResult(intent, REQUEST_1);
break;
case R.id.twoDownButton:
intent.putExtra("TAKE_DOWN_NUMBER", 2);
startActivityForResult(intent, REQUEST_1);
break;
}

}

代码 Activity

 @Override
protected void onResume()
{
super.onResume();

// Get the game state sent from the main activity
Intent intent = getIntent();
takeDownNumber = intent.getIntExtra("TAKE_DOWN_NUMBER", 0);
}
@Override
public void onClick(View v)
{
bugsMessage = "";
Intent returnIntent = new Intent(this, MainActivity.class);
returnIntent.putExtra(MainActivity.BUGS_MESSAGE, bugsMessage);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}

最佳答案

您必须使用 onCreate Bundle 来获取额外的值,使用下面的代码:

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

oneDownButton = (Button) findViewById(R.id.oneDownButton);
twoDownButton = (Button) findViewById(R.id.twoDownButton);
oneDownButton.setOnClickListener(this);
twoDownButton.setOnClickListener(this);
}
@Override
public void onClick(View v)
{
Intent intent = new Intent(this, TheCode.class);


switch (v.getId())
{
case R.id.oneDownButton:
intent.putExtra("TAKE_DOWN_NUMBER", 1);
startActivity(intent, REQUEST_1);
break;
case R.id.twoDownButton:
intent.putExtra("TAKE_DOWN_NUMBER", 2);
startActivity(intent, REQUEST_1);
break;
}

}

代码 Activity :

 public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondactivity);

Intent intent = getIntent();
Bundle bd = intent.getExtras();
if(bd != null)
{
//you must use bundle in oncreate method
takeDownNumber = bd.get("TAKE_DOWN_NUMBER");

}
}

关于java - 为什么我的值没有在 Android Studio 中使用 startActivityForResult() 在 Activity 之间传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58886381/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com