【问题标题】:Android UI elements null when returning from intent从意图返回时Android UI元素为空
【发布时间】:2020-11-26 01:09:19
【问题描述】:

我在片段中添加了一个按钮来启动一个新的活动。它可以工作,但是当从意图返回时,我无法再访问 ui 元素(来自保存片段的活动) - 它们为空。

处理此设置的正确方法是什么?我怀疑这个问题与活动生命周期有关。

我有以下配置:

  • Activity A 包含两个片段(片段 1 和片段 2)
  • 片段 1 有一个用于启动新 Activity B 的按钮。Intent 以 Activity (Activity A) 作为参数。
  • 从 Activity B 返回时,Activity A 无法再访问 Fragment 1 和 Fragment 2 中的 ui 元素。

【问题讨论】:

  • 您如何访问片段中的视图?
  • @Tenfour04 直接用它的名字就行了。

标签: android kotlin android-fragments android-intent


【解决方案1】:

此块从 A 片段启动第二个活动。而且它没有导致错误。

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View root = inflater.inflate(R.layout.fragment_a, container, false);
    Button button = (Button) root.findViewById(R.id.button);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), SecondActivity.class);
            startActivity(intent);
        }
    });

    return root;
}

其余的代码是默认的。

【讨论】:

    猜你喜欢
    • 2014-04-28
    • 1970-01-01
    • 1970-01-01
    • 2018-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多