[英]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.