使用不同类中的一个类的变量:Java

时间:2017-06-13 18:20:52

标签: java android

在Android Dev Studio工作时,我一直在研究两个类,MainActivity和Main2Activity。

MainActivity

public class MainActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE = ".com.company.name.practiceapp.MESSAGE";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void sendMessage(View view) {
    Intent intent = new Intent(this, Main2Activity.class);
    EditText editText = (EditText) findViewById(R.id.editText);
    String message = editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, message);
    startActivity(intent);

    }
}

我如何在Main2Activity中使用String消息?

注意:我浏览了许多其他类似的问题,但没有一个答案说如何使用它。这个类是公开的(如你所见),所以我无法弄清楚为什么我不能使用消息。

3 个答案:

答案 0 :(得分:0)

Intent intent = getIntent();
String text = intent.getStringExtra(".com.company.name.practiceapp.MESSAGE");

原始答案:https://stackoverflow.com/a/4233898/7339411

答案 1 :(得分:0)

在onCreate的第二个活动中,您执行以下操作:

# Example scrape config for pods
#
# The relabeling allows the actual pod scrape endpoint to be configured via the
# following annotations:
#
# * `prometheus.io/scrape`: Only scrape pods that have a value of `true`
# * `prometheus.io/path`: If the metrics path is not `/metrics` override this.
# * `prometheus.io/port`: Scrape the pod on the indicated port instead of the default of `9102`.
- job_name: 'kubernetes-pods'

  kubernetes_sd_configs:
  - role: pod

  relabel_configs:
  - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
    action: keep
    regex: true
  - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path]
    action: replace
    target_label: __metrics_path__
    regex: (.+)
  - source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
    action: replace
    regex: ([^:]+)(?::\d+)?;(\d+)
    replacement: $1:$2
    target_label: __address__
  - action: labelmap
    regex: __meta_kubernetes_pod_label_(.+)
  - source_labels: [__meta_kubernetes_namespace]
    action: replace
    target_label: kubernetes_namespace
  - source_labels: [__meta_kubernetes_pod_name]
    action: replace
    target_label: kubernetes_pod_name

您还可以指定默认值,如:

 Intent intent = getIntent();
 Bundle bundle = intent.getExtras();
 String variable = bundle.getString(EXTRA_MESSAGE);

答案 2 :(得分:0)

由于您已通过intent extra发送了消息,因此可以通过引用Main2Activity中的intent来检索它:

Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);