我正在尝试使用 listview和arrayadapter 创建应用。 我有一个自定义类(Word)和一个自定义适配器(WordAdapter)。 通过运行此代码,应用程序崩溃 这是错误:
java.lang.NullPointerException:尝试调用虚方法'void 空对象引用上的android.view.View.setTag(java.lang.Object)'
以下代码:
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class WordAdapter extends ArrayAdapter<Word> {
//datastructure to hold two textviews, so that it can be reused rather than instantiating
static class ViewHolder {
TextView textView1;
TextView textView2;
}
//sets up the arrayadapter
//@param context : specify the context (e.g current activity)
//@param words : list of words to populate the view (contains objects of custom word class)
public WordAdapter(@NonNull Context context, @NonNull ArrayList<Word> words) {
super(context, 0, words);
}
/*
Needs to override when using custom arrayadapater.
Called by the adapter class when populating data from data source into the view
@param position : position of the data in the data source
@param convertView : data from source is set as the data for this view
@param parent : parent view to which convertview gets attached
*/
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
ViewHolder viewHolder;
View list_item_view = convertView;
//checks if any reusable view is available
//list_item_view = null if no reusable view is available
if (list_item_view == null) {
viewHolder = new ViewHolder();
//convert the custom layout file into view object and inflate the parent with the view
//returns the root of the custom layout file (if attachToRoot = false)
//returns parent view to which the layout is to be attached (if attachToRoot = true)
list_item_view = LayoutInflater.from(getContext())
.inflate(R.layout.list_item, parent, false);
viewHolder.textView1 = (TextView) list_item_view.findViewById(R.id.miwok_text_view);
viewHolder.textView2 = (TextView) list_item_view.findViewById(R.id.default_text_view);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
//get the data from the position
Word word = getItem(position);
//set the miwok word
viewHolder.textView1.setText(word.getMiwokWord());
//set the default word
viewHolder.textView2.setText(word.getDefaultWord());
//retrun the view to which data is to be placed
return list_item_view;
}
}
任何人都请帮忙。
答案 0 :(得分:0)
你应该改变以下几行:
list_item_view .setTag(viewHolder);
viewHolder = (ViewHolder) list_item_view .getTag();