尝试在空对象引用上调用虚拟方法''

我收到以下错误

尝试在空对象引用上调用虚拟方法’void

android.widget.StackView.setAdapter(android.widget.Adapter)’

在这条线上

stackView.setAdapter(adapter);

完整的片段 是

public class EventsFragment extends android.support.v4.app.Fragment {

private StackView stackView;

private ArrayList<Stack_Items> list;

TypedArray eventLogo ;

String eventName[];

@Nullable

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

eventLogo= getResources().obtainTypedArray(R.array.event_stack_icon);

eventName = getResources().getStringArray(R.array.event_stack);

stackView = (StackView) getActivity().findViewById(R.id.stackView1);

list = new ArrayList<Stack_Items>();

//Adding items to the list

for (int i = 0; i < eventLogo.length(); i++) {

list.add(new Stack_Items(eventName[i], eventLogo.getResourceId(i,-1)));

}

//Calling adapter and setting it over stackView

Stack_Adapter adapter = new Stack_Adapter(getActivity().getApplicationContext(), list );

stackView.setAdapter(adapter);

adapter.notifyDataSetChanged();

return inflater.inflate(R.layout.events_layout, null);

}

}

public class Stack_Adapter extends BaseAdapter {

ArrayList<Stack_Items> arrayList;

LayoutInflater inflater;

ViewHolder holder = null;

public Stack_Adapter(Context context, ArrayList<Stack_Items> arrayList) {

this.arrayList = arrayList;

this.inflater = LayoutInflater.from(context);

}

@Override

public int getCount() {

return arrayList.size();

}

@Override

public Stack_Items getItem(int pos) {

return arrayList.get(pos);

}

@Override

public long getItemId(int pos) {

return pos;

}

@Override

public View getView(int pos, View view, ViewGroup parent) {

if (view == null) {

view = inflater.inflate(R.layout.stack_layout, parent, false);

holder = new ViewHolder();

holder.text = (TextView) view.findViewById(R.id.textView1);

holder.image = (ImageView) view.findViewById(R.id.imageView1);

view.setTag(holder);

} else {

holder = (ViewHolder) view.getTag();

}

holder.text.setText(arrayList.get(pos).getName());

holder.image.setBackgroundResource(arrayList.get(pos).getImage());

return view;

}

public class ViewHolder {

TextView text;

ImageView image;

}

}

public class Stack_Items {

String name;

Integer image;

public Stack_Items(String name, Integer image) {

this.name = name;

this.image = image;

}

public String getName() {

return name;

}

public int getImage() {

return image;

}

}

回答:

您正在执行:

stackView = (StackView) getActivity().findViewById(R.id.stackView1);

stackViewnullgetActivity().findViewById返回null

你为什么用getActivity()

在哪里stackView?您应该从正确的xml加载它。

如@Tauqir所述,您需要像这样膨胀正确的xml:

View view = inflater.inflate(R.layout.events_layout, null);

stackView = (StackView) view.findViewById(R.id.stackView1);

return view;

以上是 尝试在空对象引用上调用虚拟方法&#39;&#39; 的全部内容, 来源链接: utcz.com/qa/411406.html

回到顶部