如何在单击按钮时开始活动以生成喷气背包的结果
Posted
技术标签:
【中文标题】如何在单击按钮时开始活动以生成喷气背包的结果【英文标题】:How to start activity for result in jetpack compose on a button click 【发布时间】:2022-01-22 04:32:46 【问题描述】:实现在Java
,想在Jetpack
这个实现上写一个图标点击。按钮单击以显示语音到文本对话框:
mVoiceBtn.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
speak();
);
主要问题是在compose中创建这个特定的Intent
:
private void speak()
//intent to show speech to text dialog
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(
RecognizerIntent.EXTRA_LANGUAGE_MODEL
, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Hi Speak Somethimh");
//start intent
try
//in there was no error
//show dialog
startActivityForResult(intent, REQUEST_CODE_SPEECH_INPUT);
catch (Exception e)
//IF THERE WERE SOME ERROR
//GET MESSAGE OF ERROR AND SHOW
Toast.makeText(this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
//receive voice input and handle it
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data)
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode)
case REQUEST_CODE_SPEECH_INPUT:
if (resultCode == RESULT_OK && null != data)
//GET TEXT ARRAY FROM VOICE INTENT
ArrayList<java.lang.String> result;
result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
// SRT TO TEXT VIEW
mTextTv.setText(result.get(0));
break;
default:
【问题讨论】:
您是否尝试过在 Compose 中实现此功能?如果是这样,你的尝试是什么样的? :-) @SharanrememberLauncherForActivityResult
我有一个关于如何使用LaunchedEffect
启动的实现,但这是完全不同的目的,无法将该解决方案与所需的解决方案结合起来
好的。您是否有任何实际的 Compose 代码可以与我们分享,以便我们帮助您将其拼凑起来? :-)
你read the documentation了吗?
【参考方案1】:
记住结果的启动器活动和启动未决意图是我能找到的解决方案,可能有更好的方法。
val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
intent.putExtra(
RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM
)
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault())
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Hi Speak Somethimh")
val context = LocalContext.current
val pendIntent = PendingIntent.getActivity(context, 0, intent, 0)
var code by remember
mutableStateOf("")
val launcher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.StartIntentSenderForResult()
)
if (it.resultCode != RESULT_OK)
return@rememberLauncherForActivityResult
//GET TEXT ARRAY FROM VOICE INTENT
val result = it.data?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
if (result !== null)
code = result[0] ?: ""
Button(onClick =
launcher.launch(
IntentSenderRequest.Builder(pendIntent)
.build()
)
)
【讨论】:
当ActivityResultContracts.StartActivityForResult
合约已经存在时,你为什么要使用ActivityResultContracts.StartIntentSenderForResult()
直接获取Intent
?
知道了,谢谢,我只是在找这份合同
@Sharan 这是我推荐的实现:***.com/a/70711094/6805392以上是关于如何在单击按钮时开始活动以生成喷气背包的结果的主要内容,如果未能解决你的问题,请参考以下文章
如何防止喷气背包组合脚手架在对话框中显示时占据屏幕的整个高度