简体   繁体   中英

Android change imageView resource onItemClick in Listview

I got LIstView with 3 TextViews and 1 ImageView -using simpleAdapter with specific xml Layout

layout:

<?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>

code:

// 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 = "שגיאה התרחשה!";
        }
    }

on item click methods:

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();

            }
        });

when I click the item it does change the image to the wanted one, but its changing every 5th item image too!

how can I fix it ?

(found some outer topics that speaking about it, but I'm using the simple adapter)

You just use this custom adapter in your Listview creation and then you will write your code in this block...

use this code in your activity...

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

And then here you replace your Layout....

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;
}

 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM