0

我正在构建一个 android 应用程序,在单击图像视图时调用 OnBackPressed 函数。

这是代码 -

    ImageView imgv = (ImageView) mCustomView.findViewById(R.id.back);

    imgv.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            // TODO Auto-generated method stub

            onBackPressed();
        }
    });

现在的问题是如何使用这个 OnBackPressed 函数发送一个文本视图字符串。

4

1 回答 1

3

当您想开始第二个活动时,请使用以下代码:

Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);

当您想回到第一个活动时,请使用以下代码:

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

最后在第一个活动中,您可以通过以下方法获取返回值:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1) {
        if(resultCode == RESULT_OK) {
            String result = data.getStringExtra("result");
        }
        if (resultCode == RESULT_CANCELED) {
            // If there is no result 
        }
    }
}

一个例子 :

因此,对于使用上述代码开发您所说的示例:

在森林活动中开始第二个活动:

public void ButtonClickedMethod(View v)
{
    Intent i = new Intent(this, Second.class);
    startActivityForResult(i, 1);
}

然后在第二个活动的背压方法中使用以下代码:

@Override
public void onBackPressed()
{
    Intent returnIntent = new Intent();
    returnIntent.putExtra("result", ((TextView) findViewById(R.id.text)).getText());
    setResult(RESULT_OK,returnIntent);
    finish();
}

再次在第一个活动中使用此代码:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if (requestCode == 1) {
        if(resultCode == RESULT_OK) {
            String result = data.getStringExtra("result");
            ((Button) findViewById(R.id.button1)).setText(result);
        }
        if (resultCode == RESULT_CANCELED) {
            // If there is no result 
        }
    }
}
于 2014-11-16T14:26:29.480 回答