Android 片段到上下文?
但在课堂上:MyListAdapter我收到一个错误:Android 片段到上下文?,android,android-fragments,android-context,Android,Android Fragments,Android Context,但在课堂上:MyListAdapter我收到一个错误: listClass.add(new ListClass(json.getString("ProductId"), json .getString("ProductPrice"))); } list.setAdapter(new MyListAdapter(Fragment1.this, listClass)); fragment1类扩展了
listClass.add(new ListClass(json.getString("ProductId"), json
.getString("ProductPrice")));
}
list.setAdapter(new MyListAdapter(Fragment1.this, listClass));
fragment1类扩展了fragment。
在rowView=layoutinflater.from(//中,我只能在此处扩展上下文
而不是碎片)。
我能做什么
更新mylistadapter类:
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = LayoutInflater.from(fragment).inflate(
R.layout.pricelist, parent, false);
公共类MyListAdapter扩展BaseAdapter{
私有片段;
私有ArrayList listClass=新ArrayList();
公共MyListAdapter(Fragment1 Fragment1,ArrayList listClass1){
this.fragment=fragment1;
this.listclass=listclas1;
}
@凌驾
public int getCount(){
返回listClass.size();
}
@凌驾
公共对象getItem(int位置){
返回ListClass.get(位置);
}
@凌驾
公共长getItemId(int位置){
返回位置;
}
@凌驾
公共视图getView(int位置、视图转换视图、视图组父视图){
视图rowView=LAYOUTINGER.from(碎片)。充气(
R.layout.pricelist,父项,false);
TextView text1=(TextView)rowView.findViewById(R.id.title);
TextView text2=(TextView)rowView.findViewById(R.id.details);
text1.setText(BeanClass.get(position.phoneName));
text2.setText(BeanClass.get(position.phonePrice);
返回行视图;
}
}
要获取活动的上下文,请使用getActivity()
返回此片段当前关联的活动
public final Activity getActivity ()
然后在MyListAdapter构造函数中
list.setAdapter(new MyListAdapter(getActivity(), listClass));
使用此
list.setAdapter(新的MyListAdapter(getActivity(),listClass))
抱歉,我键入了错误的名称。。修复了它(我仍然收到一个错误)。检查文档您在哪里初始化LayoutInflater
?。您是否将活动上下文传递给MyListAdapter的构造函数并使用它?我没有初始化它。非常感谢您修复了我的问题problem@KingOmar嗯,我很高兴它错了,因为我认为答案是对的。
list.setAdapter(new MyListAdapter(getActivity(), listClass));
Context mContext; // you can remove this
LayoutInflater mInflater;
private ArrayList<ListClass> listClass = new ArrayList<ListClass>();
public MyListAdapter(Context context, ArrayList<ListClass> listClass1)
{
mContext = context; // you can remove this
mInflater = LayoutInflater.from(mContext); // get rid of this statement
mInflater = LayoutInflater.from(context); // you can directly use context
this.listclass = listClass1;
}
View rowView = mInflater.inflate(
R.layout.pricelist, parent, false);