Android使用开关按位置更改列表视图中的图像和文本

时间:2014-11-21 13:38:34

标签: android android-listview switch-statement baseadapter

我正在使用baseadapter。我成功地在列表视图中调整了图像和文本。我有3张图片和文字。现在我想在列表视图中逐个点击更改图像和文本背景 这是我的基本适配器代码

public class SlideMenuAdapter extends BaseAdapter {
private Context mContext;
private final String[] menu_items_id;

private final int[] Imageid;
TextView textView;
ImageView imageView;

private static LayoutInflater inflater = null;

public SlideMenuAdapter(Context context, String[] names, int[] Imageid)
         {
    mContext = context;

    this.Imageid = Imageid;
    this.menu_items_id = names;
    inflater = (LayoutInflater) mContext
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {

    return Imageid.length;
}

@Override
public Object getItem(int position) {

    return null;
}

@Override
public long getItemId(int position) {

    return 0;
}

@SuppressLint("ViewHolder")
@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View grid;

    grid = new View(mContext);
    grid = inflater.inflate(R.layout.azercell_slidemenu_adaper, null);
    textView = (TextView) grid.findViewById(R.id.desc);
    imageView = (ImageView) grid.findViewById(R.id.photo);

    textView.setText(menu_items_id[position]);

    textView.setTypeface(MainmoviesActivity.dejavusans);





    imageView.setImageResource(Imageid[position]);
    return grid;
}

} 这是一个主要的java代码

int[] menu_images = { R.drawable.menu_schedule, R.drawable.menu_about,
        R.drawable.menu_booking };

int[] menu_imagesover = { R.drawable.schedule_ove, R.drawable.about_over,
        R.drawable.booking_over };
private String[] menu_namesEng = { "schedule_ove", "about_over", "about_over" };






    listView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {

            TextView textView1 = (TextView) parent.findViewById(R.id.desc);

            ImageView imageView=(ImageView)parent.findViewById(R.id.photo);
            switch (position) {
            case 0:
                textView1.setTextColor(Color.parseColor("#8f332a"));
                imageView.setImageResource(menu_imagesover[position]);
                break;

            case 1:
                textView1.setTextColor(Color.parseColor("#ffffff"));
                imageView.setImageResource(menu_imagesover[position]);
                break;

            default:
                break;
            }


        }

    });

我可以更改图片和文字列表视图的第一项,当我点击第二项时,第一项的图像和文字也会再次更改。我究竟做错了什么?如果有人知道解决方案,请帮助我。

1 个答案:

答案 0 :(得分:0)

使用视图代替父级,例如:

TextView textView1 = (TextView) view.findViewById(R.id.desc);
ImageView imageView = (ImageView) view.findViewById(R.id.photo);

因为使用父级,findViewById将通过viewtree并返回第一个匹配,这始终是列表中的第一个项目。

我还建议使用RecyclerView吗? :) https://developer.android.com/reference/android/support/v7/widget/RecyclerView.html