android - 在运行方法之前等待 Activity 恢复

标签 android onactivityresult

我想在我的 onActivityResult() 方法中执行以下代码:

InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
InputMethodManager.showSoftInput(viewHolder.CertainEditTextView,InputMethodManager.SHOW_IMPLICIT);

此代码段应调出键盘,允许用户在 CertainEditTextView 中输入。

问题:它不起作用,我的理论是这是因为它在 Activity 完全加载之前运行。我认为这是因为如果我在一个单独的线程中运行这段代码,在延迟 1000 毫秒后,它可以完美运行。这为加载 Activity 提供了时间。这不是一个真正的解决方案,我正在寻找一种方法来在 Activity 加载完成后立即运行它。 onResume() 将是一个完美的方法,但我只想在调用 onActivityResult 后运行此代码 fragment 。

非常感谢所有帮助。

最佳答案

onResume 我想说的完美方法,因为它是在 onActivityResult 调用之后调用的,您只需要设置一个标志作为一个 bool 值,用于了解您是来自 onActivityResult 还是生命周期的其他部分。

Called when an activity you launched exits, giving you the requestCode you started it with, the resultCode it returned, and any additional data from it. The resultCode will be RESULT_CANCELED if the activity explicitly returned that, didn't return any result, or crashed during its operation.

You will receive this call immediately before onResume() when your activity is re-starting.

Source

更新

在提问者注意到此解决方案满足他的特定需求后,您可以考虑在输入上使用 ViewTreeObserver 以在绘制时收到通知并且它应该工作。像这样:

...
View yourView = (LinearLayout)findViewById(R.id.YOUD VIEW ID);
ViewTreeObserver vto = yourView.getViewTreeObserver(); 
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
    @Override 
    public void onGlobalLayout() { 
        yourView.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
        //We are now sure the view is drawn and should be able to do what you wanted:
        InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        InputMethodManager.showSoftInput(viewHolder.CertainEditTextView,InputMethodManager.SHOW_IMPLICIT);

    } 
});
...

关于android - 在运行方法之前等待 Activity 恢复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24165132/

相关文章:

java - 如何将首选项值获取到静态字符串变量中?

android - AOSP vanilla Android 移植到非 Nexus 设备 - 编写设备树和内核

Android 图像裁剪 Uri 异常

android - 无论应用程序状态如何,从通知正确启动 Activity

java - startActivityForResult() 返回 RESULT_CANCELED

android - 使用 for 循环访问 ImageView 数组

android - opensl中的音频播放器可以输出到两个数据接收器吗?

Android Studio 无法识别我的设备

android - 在 fragment 中开始解析结果

android - 索尼 xperia 的 onActivityResult 问题