为什么初始化额外的钥匙吗? [英] Why initialize the key of extra?

查看:125
本文介绍了为什么初始化额外的钥匙吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们想要的意图,一些数据传播给其他的应用程序组件,我们使用意向的额外费用。一个意图就是一个键值对。 我们首先定义我们的重点为公共常数,并给它一个值。例如,

When we want an intent to carry some data to another application component, we use an extra of that intent. An intent is simply a key value pair. We first define our key as a public constant, and give it a value. e.g.

public static final String extra_key = "com.example.myapp.MESSAGE";

我们还必须分配密钥需要被由意图携带的数据。例如,

We also have to assign the key the data which needs to be carried by the intent. e.g.

String extra_value = editText.getText().toString();

然后我们做出这样的意图的一个额外的:

Then we make an extra of the intent like:

intent.putExtra(extra_key, extra_value);

我的问题:

  1. 为什么关键必须公开?

  1. Why does the key have to be public?

为什么我们需要并初始化摆在首位的关键,我们为什么不能只是声明它,因为它会被分配一个值(数据 由意图反正携带)。那么,为什么不能我们做什么 如公共静态最后弦乐extra_key;

Why do we need to intialize the key in the first place, why can't we just declare it, because it will be assigned a value (the data to be carried by the intent) anyway. So why couldn't we do something like public static final String extra_key;

我已阅读,键值应该包括反向域名,使得它在其他情况下,大幅下挫的包中是唯一的。但 是给它时,它会反正是一个独特的价值点 分配其它的值,它是要由所携带的数据 意图。

I have read that the key value should include the reverse domain name so that it is unique in case other packages plunge in. But what is the point of giving it a unique value when it will anyway be assigned another value which is the data to be carried by the intent.

感谢你在前进。

推荐答案

为什么关键必须公开?

它没有。这不是一个关于意图演员或键值对的问题。这仅仅是一个关于Java变量的作用域和可见性的问题。

It doesn't. This is not a question about intent extras or key value pairs. It is simply a question about Java variable scope and visibility.

在调用类:

intent.putExtra("KEY_NAME", "Key_Value");

在接收组件:

intent.getStringExtra("KEY_NAME");

这工作就好了。 良好做法是让公共最后静态,使发送者和接收者可以使用相同的常量名。

This work just fine. Good practice is to make it public final static so that the sender and receiver can use the same constant name.

为什么我们需要并初始化摆在首位的关键,我们为什么不能只是声明它,因为它总要被分配一个值(数据由意图来进行)。那么,为什么不能,我们做这样的事情

见上面。关键的名字无非是一个字符串。关键的做的不可以承载数据,该值一样。

See above. The key name is nothing more than a string. The key does not carry the data, the value does.

我已阅读,键值应该包括反向域名

这是没有意义的。关键值是任何数据发送者想要发送到接收器。还是你的意思键名?关键的名称必须由接收方知道,如果这目的是启动外部组件,则必须使用键名由接收机定义。如果打算为内部组件,那么你定义的名称是任何你想要的。我看不出有什么充分的理由包括包名称。它只是占用更多的内存。

This makes no sense. The key value is whatever data the sender wants to send to the receiver. Or did you mean the key name? The name of the key must be know by the receiver so if this intent is to start an external component, then you must use the key name as defined by the receiver. If the intent is for an internal component, then you define the name to be whatever you want. I can see no good reason to include the package name. It just uses more memory.

这篇关于为什么初始化额外的钥匙吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆