【问题标题】:Android: replacing text in activity after click event on fragment button [duplicate]Android:在片段按钮上单击事件后替换活动中的文本[重复]
【发布时间】:2016-12-27 15:04:54
【问题描述】:

我有很多 NPE,想知道您如何管理这项常见任务。

  1. 我的片段中有一个按钮,这里是 WelcomeFragment。

  2. 按钮将被点击,事件在 MainActivity 类中处理。

  3. 片段是 NPE,视图也是...

这是我的 MainActivity 的代码 sn-p:

@Override
public void onClick(View v) { 
    switch (v.getId()) {
        case R.id.button1:
            ...
            WelcomeFragment welcomeFragment = (WelcomeFragment) getFragmentManager().findFragmentByTag(WelcomeFragment.WELCOME_FRAGMENT_TAG);
            if (welcomeFragment == null){
                welcomeFragment = new WelcomeFragment();
            }
            View view = welcomeFragment.getView();
            if (view == null){
                view = new View(this);
            }
            TextView text1 = (TextView) view.findViewById(R.id.welcomeFragmentHeader);
            text1.setText(newTextToShow + resStr);
            break;

...

【问题讨论】:

  • NPE 是从哪里解雇的?更多细节? ..

标签: android android-fragments android-activity android-event


【解决方案1】:

我假设您的应用程序在您第一次单击此按钮时因 NPE 而崩溃,此时没有 WelcomeFragment 实例:

(WelcomeFragment) getFragmentManager().findFragmentByTag(WelcomeFragment.WELCOME_FRAGMENT_TAG);

返回 null,因此您输入 if 语句并构造一个 WelcomeFragment。

这不是制作片段的正确方法。它的内容不会以这种方式膨胀,因此它没有视图。因此,您稍后对 (TextView) view.findViewById(R.id.welcomeFragmentHeader); 的调用也返回 null。因此,您在下一行的空对象上调用 setText(),并获得 NPE。

您需要正确地将片段添加到您的活动中作为here 中的大纲,或更改您的应用逻辑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-14
    • 2017-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多