Android上的startActivityForResult

时间:2016-09-14 11:41:44

标签: java android

我尝试使用startActivityForResult开发一些非常基本的代码,我总是遇到一个烦人的问题:从主要活动(只包含一个" hello word" editText)我调用一个新的活动它只包含一个TextView,一个空的listView和一个ImageButton。当我点击ImageButton时,它会返回" ok"在我的mainActivity的意图内,并将其打印到" hello word" editText但没有任何反应。我已经阅读了有关如何使用" StartActivity for result"的所有主题。但我没有发现任何帮助。请帮助我。

我的代码如下:

MainActivity

   public class MainActivity extends AppCompatActivity {

    TextView hw;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        hw = (TextView) findViewById(R.id.hw);
        hw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getApplicationContext(),DeviceListActivity.class);
                int resultCode = -1;
                startActivityForResult(intent,resultCode);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 1) {
            if(resultCode == Activity.RESULT_OK){
                String result=data.getStringExtra("result");
                hw.setText(result);

            }
            if (resultCode == Activity.RESULT_CANCELED) {
                //Write your code if there's no result
            }
        }
    }
    }

DeviceListActivity:

public class DeviceListActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.device_list);

    final ImageButton nextBtn = (ImageButton) findViewById(R.id.nextBtn);
    nextBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent returnIntent = new Intent();
            String result = "Tout va bien!";
            returnIntent.putExtra("result",result);
            onActivityResult(1,1,returnIntent);
            setResult(Activity.RESULT_OK, returnIntent);
            finish();
        }
    });
}
}

1 个答案:

答案 0 :(得分:1)

您的MainActivity更改中的

Intent intent = new Intent(getApplicationContext(),DeviceListActivity.class);
int resultCode = -1;
startActivityForResult(intent,resultCode);

Intent intent = new Intent(getApplicationContext(),DeviceListActivity.class);
int resultCode = 1;
startActivityForResult(intent,resultCode);

并在 DeviceListActivity 中将代码替换为:

Intent returnIntent = new Intent();
        String result = "Tout va bien!";
        returnIntent.putExtra("result",result);
        setResult(Activity.RESULT_OK, returnIntent);
        finish();

希望它会帮助你。