为ListFragment中的每个项添加不同的图标

时间:2013-11-01 11:43:43

标签: android android-listfragment

我已经成功设置了一个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();
}

}

1 个答案:

答案 0 :(得分:2)

创建一个Drawable ID数组,就像在适配器中创建month[]数组一样。

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

然后访问数组,就像使用month数组设置TextView

的文本一样
icon.setImageResource(drawables[position]);