android - Android 中 getTextView 的 NullPointerException

标签 android textview android-framelayout

所以我在一个名为 ItemEnergyGreen 的类中有这个 getter 函数:

public TextView getTextView(FrameLayout fl) {
    textView = (TextView) fl.findViewById(R.id.textview_energyOrange_quantity);
    return textView;
}

现在我想从另一个类调用这个方法:

//Item Energy Green
    itemEnergyGreenFrameLayout      = (FrameLayout) inflater.inflate(R.layout.item_energy_green_layout, null, false);
    itemEnergyGreenQuantityTextView = itemEnergyGreen.getTextView(itemEnergyGreenFrameLayout);
    btn_ItemEnergyGreen             = (ImageButton) itemEnergyGreenFrameLayout.findViewById(R.id.btn_energyGreenItem_use);
    btn_ItemEnergyGreen.setOnClickListener(this);

函数调用在第 2 行,我将 frameLayout 传递给 getter 函数,但我的 ItemEnergyGreen 类中的 textView 始终为 NULL。

当我想在我的 View 上调用 setText 时发生错误:

public void itemEnergyGreenUpdateNumber() {
    int quantity = itemEnergyGreen.getQuantity();
    String qstring = String.valueOf(quantity);
    itemEnergyGreenQuantityTextView.setText(qstring);
}

这是膨胀的 XML-FrameLayout:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ItemEnergyGreenFrameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<ImageButton
    android:id="@+id/btn_energyGreenItem_use"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scaleType="fitXY"
    android:src="@drawable/item_energydrink_green" >
</ImageButton>

<TextView
    android:id="@+id/textview_energyGreen_quantity"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:background="#F00"
    android:clickable="false"
    android:padding="2dp"
    android:textColor="#FFF"
    android:textStyle="bold" >
</TextView>
</FrameLayout>

这是为什么?

附言。在调用 getter 函数时,itemEnergyGreen 对象已经初始化。

谢谢你的回答,如果这是一个转储问题,我很抱歉,但我对此很着迷。

最佳答案

textView in my ItemEnergyGreen class is always NULL.

findViewById 在当前 View 层次结构中查找 View 。可能 TextView 不是 FrameLayout 的子级。因此初始化失败导致 NullPointerException

另一个原因可能是您引用了错误的 ID。

编辑:

错误引用的ID

<TextView
    android:id="@+id/textview_energyGreen_quantity"

改变这个

textView = (TextView) fl.findViewById(R.id.textview_energyOrange_quantity);

textView = (TextView) fl.findViewById(R.id.textview_energyGreen_quantity);

关于android - Android 中 getTextView 的 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22735216/

相关文章:

java - Android map 中的空指针(使用 Google Maps api v2)

android - 使 ExpandableListView 和 Textview 一起滚动

android - 是否可以在 onLayout 事件中将 View 添加到布局?

javascript - 在 React-Native Expo 上接收 MQTT 消息

Android 2 模拟器通信

Android捏放大图像

android - frameLaout 的 TouchListener

android - 显示版本名称

android如何在textview中设置超链接

android - Frame Layout不支持fling手势吗?