gpt4 book ai didi

java - 将字符串或变量从对话框传递到 Android Activity

转载 作者:行者123 更新时间:2023-12-01 08:54:36 24 4
gpt4 key购买 nike

我想从对话框中隐式传递两个字符串或变量以供另一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com