我求助你作为一个新的java / android程序员。 我试图通过我的自定义适配器传递“this”,以在SherlockFragment中设置ListView。不幸的是,在我的onCreateView中编译时,我在未定义的构造函数中设置适配器(new LeatherAdapter(this))时出现错误。有人可以一步一步地解释我的问题吗?
import java.util.ArrayList;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragment;
public class LeatherTab extends SherlockFragment {
private ListView leather_listview;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.leather_fragment, container, false); //Fragment Layout inflated
leather_listview = (ListView) view.findViewById(R.id.leather_list); // List is initialized
leather_listview.setAdapter(new LeatherAdapter(this)); //Custom list adapter passes Context
return view;
}
}
class SingleRow {
String title;
String description;
int image;
SingleRow(String title, String description, int image) {
this.title=title;
this.description=description;
this.image=image;
}
}
class LeatherAdapter extends BaseAdapter {
ArrayList<SingleRow> list;
Context context;
public LeatherAdapter(Context c) {
context = c;
list = new ArrayList<SingleRow>();
Resources res = c.getResources();
String[] titles = res.getStringArray(R.array.leather_list_titles);
String[] descriptions = res.getStringArray(R.array.leather_list_description);
int[] images = {R.drawable.belt, R.drawable.wallet, R.drawable.coincase};
for (int i=0;i<3;i++)
{
new SingleRow(titles[i], descriptions[i], images[i]);
}
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int i) {
return list.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.single_row, viewGroup, false);
TextView title = (TextView) row.findViewById(R.id.leather_title);
TextView description = (TextView) row.findViewById(R.id.leather_description);
ImageView image = (ImageView) row.findViewById(R.id.leather_icon);
SingleRow temp = list.get(position);
title.setText(temp.title);
description.setText(temp.description);
image.setImageResource(temp.image);
return row;//returns the rootView of single_row.xml
}
}
答案 0 :(得分:2)
更改此
leather_listview.setAdapter(new LeatherAdapter(this));
到
leather_listview.setAdapter(new LeatherAdapter(getActivity());
http://developer.android.com/reference/android/app/Fragment.html#getActivity()
public final Activity getActivity ()
返回此片段当前与之关联的活动。