我想从对话框中隐式传递两个字符串或变量以供另一个 Activity 使用,同时打开该 Activity 。
对话框
String city = addresses.get(0).getLocality();
String category = "Hazard";
AlertDialog.Builder prompt = new
AlertDialog.Builder(MapsActivity.this);
prompt.setCancelable(false)
.setPositiveButton("Mineralization", new
DialogInterface.OnClickListener() {
.setPositivetiveButton("Geohazard", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
startActivity(new
Intent(getApplicationContext(),MapsActivity.class));
//i want to pass the String city and category here
}
}
)
AlertDialog alert = prompt.create();
alert.setTitle("Please select an option");
alert.show();
TextView myTextView = (TextView) findViewById(R.id.PSString);
myTextView.setText(city);
新 Activity
package com.example.boneyflesh.homepage;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class GeohazardResults extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_geohazard_results);
}
}
我该怎么做?我应该在 onClickListener 上写什么以及在新 Activity 上做什么才能获取字符串?
最佳答案
不要在 onClick 方法中执行类似的操作
startActivity(new Intent(getApplicationContext(),MapsActivity.class));
您可以通过 Intent 将两个字符串传递给 onClick 方法内的 MapsActivity
,如下所示
Intent lIntent = new Intent(getApplicationContext(), MapsActivity.class);
lIntent.putExtra("city", city);
lIntent.putExtra("category", category);
startActivity(lIntent);
并在MapsActivity
中检索这些值,如下所示
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_geohazard_results);
String city = getIntent().getStringExtra("city");
String category = getIntent().getStringExtra("category");
}
关于java - 将字符串或变量从对话框传递到 Android Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42129578/