Android在Listview中更改imageView资源onItemClick

时间:2014-03-24 11:03:21

标签: java android listview

我使用3个TextView和1个ImageView获取LIstView - 使用具有特定xml布局的simpleAdapter

布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tvSongName"
        android:layout_width="200dp"
        android:layout_height="50dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:background="@drawable/plank1"
        android:gravity="center"
        android:text="TextView"
        android:textSize="14sp"
        android:textStyle="bold" />

    <ImageView 

        android:id="@+id/ivFav"
        android:layout_width="150dp"
        android:layout_height="50dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="10dp"
        android:src="@drawable/plank4_empty" />

    <TextView
        android:id="@+id/tvDate"
        android:layout_width="170dp"
        android:layout_height="50dp"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/tvSongName"
        android:background="@drawable/plank2"
        android:gravity="center"
        android:text="TextView"
        android:textSize="14sp"
        android:textStyle="bold" />

    <TextView android:layout_centerVertical="true"
        android:id="@+id/tvArtist"
        android:layout_width="150dp"
        android:layout_height="50dp"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/ivFav"
        android:background="@drawable/plank3"
        android:gravity="center"
        android:text="TextView"
        android:textSize="14sp"
        android:textStyle="bold" />

</RelativeLayout>

// get all the JSON Objects of today songs and return in array
    public JSONArray getJSONs_array() throws ClientProtocolException, IOException, JSONException {
        StringBuilder url = new StringBuilder(current_url);
        HttpGet get = new HttpGet(url.toString());
        HttpResponse r = client.execute(get);
        int status = r.getStatusLine().getStatusCode();
        if (status == 200) {
            HttpEntity e = r.getEntity();
            String data = EntityUtils.toString(e);
            JSONArray JSONarray = new JSONArray(data);
            return JSONarray;
        } else {
            return null;
        }

    }

    public class Read_today_songs extends AsyncTask<String, Integer, String> {

        boolean running = true;

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            pbPlaylist.setVisibility(View.VISIBLE);
        }

        @Override
        protected String doInBackground(String... params) {
            try {
                jsonArray = getJSONs_array();
                if (jsonArray.length() > 0) {
                    today_song_item = new ArrayList<Map<String, String>>();
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        // singerName = jsonObject.getString("singerName");
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("singerName", jsonObject.getString("singerName"));
                        map.put("songName", jsonObject.getString("songName"));
                        map.put("date", jsonObject.getString("date"));
                        today_song_item.add(map);
                    }
                    return "true";
                } else
                    return "false";
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            // PrograssBar Disapper
            pbPlaylist.setVisibility(View.GONE);
            // check if got the today_song_itemArrayList<Map<String, String>>()
            // with values
            if (result.contains("true")) {
                adapter = new SimpleAdapter(thePlayList.this, today_song_item, R.layout.playlist_item_layout, new String[] { "singerName", "songName", "date" }, new int[] { R.id.tvArtist, R.id.tvSongName, R.id.tvDate });
                lvSongsList.setAdapter(adapter);
            } else
                fb_msg = "שגיאה התרחשה!";
        }
    }
项目点击方法

lvSongsList.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // TODO Auto-generated method stub

                change_selected_song_to_fav_or_not(view);

                // TextView TextView_SongArtistFromView =
                String SongArtistFromView = ((TextView) view.findViewById(R.id.tvArtist)).getText().toString();
                String SongNameFromView = ((TextView) view.findViewById(R.id.tvSongName)).getText().toString();

                // Will hold the HashMap of vlaues
                HashMap<String, String> queryValuesMap = new HashMap<String, String>();
                queryValuesMap.put("singerName", SongArtistFromView);
                queryValuesMap.put("songName", SongNameFromView);

                // Call for function that adding the new HashMap to the db
                // insert the song to favs -> 1=true    -1=false
                long inserted = dbTools.insertNewFav(queryValuesMap);
                if (inserted >= 1) {
                    Toast.makeText(thePlayList.this, "שיר נוסף למועדפים!", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(thePlayList.this, "שגיאה לא מוכרת בהוספת שיר! יש לנסות שוב מאוחר יותר!", Toast.LENGTH_SHORT).show();
                }

                // DELETE ALL ROWS --------------> delete line when all is done
//              dbTools.deleteAllRows();

            }
        });

当我点击该项目时,它确实将图像更改为想要的图像,但它也会更改每个第5个项目图像!

我该如何解决?

(找到了一些关于它的外部话题,但我使用简单的适配器)

1 个答案:

答案 0 :(得分:0)

您只需在Listview创建中使用此自定义适配器,然后您将在此块中编写代码...

在您的活动中使用此代码......

CustomAdapter mAdapter = new CustomAdapter(this, R.layout.listitem, mListItems);
mPullRefreshListView.setAdapter(mAdapter);

然后在这里替换你的布局......

public class CustomAdapter extends ArrayAdapter<Sample> {

public ArrayList<Sample> mlist;
public Context context;
public LayoutInflater inflater;

public CustomAdapter(Context context, int resource, ArrayList<Sample> mlist) {
    super(context, resource);
    this.mlist = mlist;
    this.context = context;
    inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getPosition(Sample item) {
    return super.getPosition(item);
}

@Override
public Sample getItem(int position) {
    return mlist.get(position);
}

@Override
public int getCount() {
    return mlist.size();
}

@Override
public long getItemId(int position) {
    return super.getItemId(position);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    convertView = inflater.inflate(R.layout.listitem, null);//Replace your layout....
    TextView text1 = (TextView) convertView.findViewById(R.id.item1);
    TextView text2 = (TextView) convertView.findViewById(R.id.item2);
    text1.setText(mlist.get(position).getListitem1());
    text2.setText(mlist.get(position).getListitem2());
    text2.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // you just put your Logic here And use this custom adapter to
            // load your Data By using this particular custom adapter to
            // your listview
                            //Change your imageview here

        }
    });
    return convertView;
}

 }