[英]How to start an activity which calls a method from a different class?
我有一个活动,该活动将字符串数据类型传输到另一个活动,该活动然后使用该字符串并从另一个返回一个字符串的类中调用一个方法。 我想使用该方法在当前活动中显示字符串。
因此,从视觉上看,它是(活动1)-字符串->(活动2)。 活动2使用该字符串来调用其他java类中的方法,该方法返回一个我想在屏幕上显示的类型字符串以及一些按钮。
所以一些伪代码:
在另一个java类中,方法是:
public static String getStringexample(String n) {
return "hello" + " " + n;
}
我的活动课是:
public class manage extends Activity {
protected void onCreate(bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContainerView(R.layout.activity_manage);
Intent intent = getIntent();
String example = intent.getExtras().getString("intentid");
我在此之后迷路了..不确定如何使用我从意图中获得的内容在Java代码中显示在屏幕上。
您可以通过以下方式开始活动
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);
然后从第二活动返回到第一活动
Intent returnIntent = new Intent();
returnIntent.putExtra("result",yourdata);
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) {
//Write your code if there's no result
}
}
}
活动之间的信息以“附加”形式传递。 那只是字符串键和值的集合。
双方都需要使用相同的键,因此用目标活动期望的键定义静态最终字符串。
然后使用键从附加项中读取值,然后从那里进行:
public class DestinationActivity extends Activity {
// let your callers know how to pass you the information you need
public static final String EXTRA_N = "n";
private TextView resultText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_destination);
resultText = (TextView) findViewById(R.id.resultText);
// get the information you was passed
Intent intent = getIntent();
String n = intent.getStringExtra(EXTRA_N);
// do your transformation using the other class
String example = DifferentClass.getStringexample(n);
// display the transformed string
resultText.setText(example);
}
// ...
}
呼叫活动发送如下信息:
Intent intent = new Intent(this, DestinationActivity.class);
intent.putExtra(DestinationActivity.EXTRA_N, "foo");
startActivity(intent);
祝好运
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.