我真的被困在这个问题上了。我正在尝试做一个简单的文本切换器,它将增加数量并根据数量更新价格。现在在我的 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/