9

我真的坚持这一点。我正在尝试做一个简单的文本切换器,它将增加数量并根据数量更新价格。现在在我的 xml 中,我在 TextSwitcher 中有类似 TextView 的东西,只是为了增加数量。我得到了文本视图findViewById(R.id.quantity)

所以这是我必须找到的设置增量数量(我正在实现 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 片段:

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

4 回答 4

28

来自TextSwitcher 的文档

setText (CharSequence text) 设置下一个视图的文本并切换到下一个视图。这可用于将旧文本动画化并动画化下一个文本。

这意味着您将需要至少两个文本视图,一个包含旧文本,一个用于接收新文本并进行动画处理。以下 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>
于 2011-11-24T22:28:46.797 回答
1

确保setContentView在查找 TextSwitcher 之前致电

于 2011-06-14T20:17:52.263 回答
1

嗯..有趣,我在这里也遇到了同样的问题。就我而言,有两个问题,首先我从 makeView 返回 null。我相信这不是你的情况,因为你从 findViewById 获取它的引用(但要注意,有时这个方法会失败并返回一个空引用,我建议你在那里放一个断点并确保你没有空指针)。

我遇到的第二个问题(我认为这也可能是您的问题)是 TextSwitcher 显然不希望有任何子视图,因此您不应该像这样做那样将 TextView 放入其中。尝试删除该 TextView 并查看它是否有效。

于 2011-09-27T15:41:28.840 回答
1

我遇到了与 findViewById 返回 null 相同的奇怪问题。经过几个小时的挖掘,我终于能够解决这个问题:这是我的代码中的一个错误。您很有可能遇到类似的错误。

我的代码是(不是原始代码,用于说明目的):

public class MyTextSwitcher extends TextSwitcher {
public MyTextSwitcher(Context context, AttributeSet attrs) {
    super(context);
}

错误在于构造函数调用。构造函数中的代码应更改为以下内容以使工作正常:

super(context, attrs); // note the extra attrs parameter

该错误(以及其他类中的类似错误)可能导致所有“新”定义的资源对findViewById.

惭愧,我今天犯了两次同样的错误!

于 2011-11-16T10:26:59.180 回答