0

我的自定义适配器的 getView() 方法中有一个 TextView 引用,如下所示:

final TextView favs = (TextView) convertView.findViewById(R.id.nofavs);

这很好,但是,当我尝试在下一行中立即设置其文本时,我收到 NullPointerException 错误:

final TextView favs = (TextView) convertView.findViewById(R.id.favs);
favs.setText("3 favourites");

编辑: LogCat

07-22 21:07:52.815: E/AndroidRuntime(31514): FATAL EXCEPTION: main
07-22 21:07:52.815: E/AndroidRuntime(31514): java.lang.NullPointerException
07-22 21:07:52.815: E/AndroidRuntime(31514):    at com.guide.Tab01_FavAdapter.getView(Tab01_FavAdapter.java:65)
07-22 21:07:52.815: E/AndroidRuntime(31514):    at android.widget.AbsListView.obtainView(AbsListView.java:2461)
07-22 21:07:52.815: E/AndroidRuntime(31514):    at android.widget.GridView.onMeasure(GridView.java:1030)
07-22 21:07:52.815: E/AndroidRuntime(31514):    at android.view.View.measure(View.java:15473)
07-22 21:07:52.815: E/AndroidRuntime(31514):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5056)
07-22 21:07:52.815: E/AndroidRuntime(31514):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
...
4

2 回答 2

0

您应该首先检查转换视图是否为空,如果它的空值使视图膨胀...

if(convertView == null) {
  LayoutInflater inflater = getLayoutInflater();
  convertView = inflater.inflate(R.layout.row, parent, false);
}

阅读此getView(...)

于 2013-07-22T20:42:38.750 回答
-1

您应该使用nofavs.setText("3 facourites"),因为变量的名称是 nofavs。

于 2013-07-22T19:56:36.213 回答