如何从一个新的意图回传给变量来创建它的Andr​​oid类它的、变量、意图、回传

2023-09-12 06:00:52 作者:万物不及XX

我知道我的标题可能有点令人费解,但我真的很困惑,也想不出更好的标题。

I know my title may be a little convoluted but I am really quite confused and couldn't think of a better title.

我的问题: 我有一个创建一个新的意图一个主类。这种新的意图基本上是一个具有的EditText 在里面,一个弹出按钮。

My problem: I have a main class that creates a new intent. This new intent is basically just a popup with an EditText in it and one button.

我的主类创建意图是这样:

Intent i = new Intent("com.stevedub.GS.INPUTMPG");
startActivity(i);

我想要做的就是以某种方式获取数据,用户输入到的EditText 意图并使用整在我的主类进行计算。我只是不知道如何做到这一点。

What I want to do is somehow get the data that the user inputs into the EditText in the new Intent and use that integer in my main class to do calculations. I just have no idea how to accomplish this.

这是在code,我为我所用的第二类新意图

This is the code I have for my second class that is used for the new Intent.

public class InputMPG extends Activity {

EditText mpg;
Button b;
String ans;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.inputmpg);

    mpg = (EditText) findViewById(R.id.MPGinput);
}

现在新的活动是一类只是准系统,因为我不知道我是否应该初始化按钮和的EditText 在类或没有。 任何人都指着我在正确的方向将是极大的AP preciated。

Now the new activity is just the barebones of a class because I don't know if I should be initializing the button and the EditText in that class or no. Anyone pointing me in the right direction would be greatly appreciated.

在此先感谢。

推荐答案

你将需要做的是一个事物的组合。

What you will need to do is a combination of things.

首先,使用启动活动:

Intent intent = new Intent("com.stevedub.GS.INPUTMPG");
startActivityForResult(intent, RETURN_CODE);

然后在你的InputMPG类,设置以下的返回值:

Then in your InputMPG class, set the Return value with the following:

Intent returnIntent = new Intent();
returnIntent.putExtra("result", editText.getText());
setResult(RESULT_OK, returnIntent);

终于收到你原来的活动数据使用onActivityResult方法:

Finally to receive the data in your original Activity use the onActivityResult method:

public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RETURN_CODE && resultCode == RESULT_OK) {
        //get value from intent
    } 
}