0

我已经成功地设置了一个 ListFragment,每个字符串/项目旁边都有一个简单的图标。

现在我想为列表中的每个项目/字符串添加不同的图标/图像。

我怎么能做到这一点?我在使用正常活动之前已经完成了它,但没有使用 ListFragments。

提前致谢...

ListFragment 类:

public class Fragment2 extends ListFragment {

public class MyListAdapter extends ArrayAdapter<String> {

    Context myContext;

    public MyListAdapter(Context context, int textViewResourceId,
            String[] objects) {
        super(context, textViewResourceId, objects);
        myContext = context;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // return super.getView(position, convertView, parent);

        LayoutInflater inflater = (LayoutInflater) myContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View row = inflater.inflate(R.layout.row, parent, false);
        TextView label = (TextView) row.findViewById(R.id.month);
        label.setText(month[position]);
        ImageView icon = (ImageView) row.findViewById(R.id.icon);

        //Set icon here
        icon.setImageResource(R.drawable.ic_launcher);

        return row;
    }

}

String[] month = { " ", "Abstract", "Animal", "Anime", "Artistic", "Cartoon", "Comics",
        "Celeberity", "Cars", "Fantasy", "Food" };

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    /*
     * ListAdapter myListAdapter = new ArrayAdapter<String>( getActivity(),
     * android.R.layout.simple_list_item_1, month);
     * setListAdapter(myListAdapter);
     */
    MyListAdapter myListAdapter = new MyListAdapter(getActivity(),
            R.layout.row, month);
    setListAdapter(myListAdapter);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragments_layout2, container, false);
}

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    Toast.makeText(getActivity(),
            getListView().getItemAtPosition(position).toString(),
            Toast.LENGTH_LONG).show();
}

}
4

1 回答 1

2

制作一个Drawableid 数组,就像您month[]在适配器中制作数组一样。

int[] drawables = {R.drawable.icon1, R.drawable.icon2, R.drawable.icon3, R.drawable.icon4};

然后像使用月份数组设置文本一样访问数组TextView

icon.setImageResource(drawables[position]);
于 2013-11-01T11:52:39.183 回答