android – TextSwitcher NullPointer错误

我真的很困惑.我正在尝试做一个简单的文本交换器,它将增加数量并根据数量更新价格.现在在我的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));

谁能让我知道我做错了什么?我一直在这一行得到我的nullpointer:

switcher.setFactory(this);

这是XML片段:

<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.

这意味着您将需要至少两个文本视图,一个包含旧文本,另一个用于接收新文本和动画.
以下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性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...