android - TextSwitcher NullPointer 错误

标签 android textview nullpointerexception android-ui

我真的被困在这个问题上了。我正在尝试做一个简单的文本切换器,它将增加数量并根据数量更新价格。现在在我的 xml 中,我在 TextSwitcher 中有一个类似 TextView 的东西,只是为了增加数量。我使用 findViewById(R.id.quantity) 获取 TextView 。

所以这就是我必须找到的设置增量数量的方法(我正在实现 ViewFactory)

switcher = (TextSwitcher) findViewById(R.id.switcher);
switcher.setFactory(this);
quantity = (TextView) findViewById(R.id.quantity);

我也覆盖了 makeView()

@Override
     public View makeView() {
        return quantity;
    }

此外,当按下增量按钮时,我会增加计数器并将切换器上的文本设置为当前计数。像这样:

switcher.setText(String.valueOf(currentQuantity));

谁能告诉我我做错了什么??我一直在这一行得到我的空指针:

switcher.setFactory(this);

这是 XML fragment :

<TextSwitcher android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/switcher">
            <TextView android:text="TextView" android:id="@+id/quantity" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
        </TextSwitcher>

最佳答案

来自Documentation for TextSwitcher :

setText (CharSequence text) Sets the text of the next view and switches to the next view. This can be used to animate the old text out and animate the next text in.

这意味着您至少需要两个 TextView ,一个包含旧文本,一个用于接收新文本并在其中添加动画。 以下 XML 应该有效:

    <TextSwitcher 
        android:id="@+id/counter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="1"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    </TextSwitcher>

关于android - TextSwitcher NullPointer 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6349052/

相关文章:

android - NullPointerException : int android. 部件.Editor$SelectionModifierCursorController.getMinTouchOffset()

java - 什么是NullPointerException,我该如何解决?

android - 无提示安装安卓APK

java - GestureDetector.SimpleOnGestureListener 不考虑 View 比例因子?

java - Asynctask等待函数导致错误

android - 我怎样才能获得相机 2 中 TextureView 预览大小的图像

android - 删除 TextView 中不需要的行间距

android - 用 TextView 显示小数

java - 使用 Jackson 序列化空值

android - ArrayAdapter 中的 ConvertView 为 null