我想从意图中获取另一个活动中的字符串.这是创建我的意图的方法
val intent = Intent(this, Main2Activity::class.java)
intent.putExtra("samplename", "abd")
startActivity(intent)
Run Code Online (Sandbox Code Playgroud)
如何在另一个活动中获得此意图的价值
zas*_*saz 36
找到答案,在下一个活动中,你必须这样做才能获得字符串:
val ss:String = intent.getStringExtra("valor")
Run Code Online (Sandbox Code Playgroud)
Sam*_*Sam 15
加载
val value: String = txt_act_main.text.toString() // or just your string
val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("value", value)
startActivity(intent)
Run Code Online (Sandbox Code Playgroud)
//选项2所有内部类都应实现为Serializable
getIntent().putExtra("complexObject", clickedTitle);
Run Code Online (Sandbox Code Playgroud)
得到
var bundle :Bundle ?=intent.extras
var message = bundle!!.getString("value") // 1
var strUser: String = intent.getStringExtra("value") // 2
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
Run Code Online (Sandbox Code Playgroud)
//选项2
var myProg = intent.getSerializableExtra("complexObject") as MenuModel
Run Code Online (Sandbox Code Playgroud)
隐式(与其他应用共享)
val value: String = txt_act_main.text.toString()
var intent = Intent()
intent.action = Intent.ACTION_SEND
intent.putExtra(Intent.EXTRA_TEXT, value)
intent.type="text/plain"
startActivity(Intent.createChooser(intent,"Share to "))
Run Code Online (Sandbox Code Playgroud)
小智 7
您可以检查意图值是否为空
val bundle :Bundle ?=intent.extras
if (bundle!=null){
val message = bundle.getString("object") // 1
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
Run Code Online (Sandbox Code Playgroud)
可以使用此代码:
val bundle = intent.extras
var sampleName: String = ""
if (bundle != null) {
sampleName = bundle.getString("samplename")
}
Run Code Online (Sandbox Code Playgroud)
在 Main2Activity 中,您可以使用如下代码:
val intent = getIntent();
val myValue = intent.getStringExtra("key")
Log.d(TAG,"myValue"+myValue)
Run Code Online (Sandbox Code Playgroud)
接受的答案不能解决意图不存在的情况。因为当密钥不存在于意图中时,甚至getStringExtra()会给你null它的签名指示 aString而不是 a String?。
您可以使用val text:String = intent.getStringExtra(intentKey) ?: ""来确保没有发生 NPE。
但这里还有一个答案:
这是针对以下情况,您尝试从意图中检索字符串,如果该值存在,我们将获得该值,否则,它将返回到前一个屏幕,因为该意图至关重要。会发生一些错误,但我们不想使活动崩溃。
private fun getStringFromIntentOrShowError(intentKey: String):String {
val text:String? = intent.getStringExtra(intentKey)
if (text == null) {
showDialog(
"Error",
"No $intentKey found"
) {
it.dismiss()
finish()
}
return ""
}
return text
}
// I use anko to show a dialog, you can use your one.
private fun showDialog(
title:String,
message:String,
yesButtonCallback: (d:DialogInterface) -> Unit
) {
alert(message, title){ yesButton{
yesButtonCallback(it)
} }.show()
}
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样使用它:
val text:String = getStringFromIntentOrShowError("asd")
Run Code Online (Sandbox Code Playgroud)
并且文本将始终具有值
| 归档时间: |
|
| 查看次数: |
41408 次 |
| 最近记录: |