无法将图标添加到android ListView中的前3个列表项?

时间:2015-05-14 02:44:10

标签: android json listview icons

最近,我构建了一个应用程序,我可以通过json从Web检索结果。它显示的是一个简单的信息。我心想,自定义列表视图看起来很简单,只有文本,所以我现在要做的是在listitem的左侧为前3个列表项添加图标,但事情变得复杂,因为我有来自网络的json数据。我发现很难将逻辑实现到当前代码。毕竟,我想做的就是在前3个项目列表中添加图标。我在下面设置了我的示例代码(抱歉不整齐的代码!)。

是否可以在当前代码中设置逻辑?或者我应该重新开始?有一些解决方案吗?

protected void onPostExecute(JSONObject jsonobject) {

        try {

            // Locate the array name in JSON

            jsonarray = jsonobject.getJSONArray("infolist");

            world = new ArrayList<InfoListData>();
            // Create an array to populate the spinner
            worldlist = new ArrayList<String>();
            for (int i = 0; i < jsonarray.length(); i++) {

                HashMap<String, String> map = new HashMap<String, String>();
                jsonobject = jsonarray.getJSONObject(i);

                InfoListData worldpop = new InfoListData();
                worldpop.set_loto_date(jsonobject.optString("loto_date"));
                worldpop.set_info_id(jsonobject
                        .optString("takarakuji_id"));
                worldpop.set_numbertimes(jsonobject.optString("id"));
                worldpop.set_title(jsonobject.optString("title"));
                world.add(worldpop);

                worldlist.add(jsonobject.optString("title") + "\n"
                        + jsonobject.optString("info_date"));

            }

            str = jsonarray.toString();
            try{
                JSONArray jArray = new JSONArray(str);

                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject json = null;
                    json = jArray.getJSONObject(i);

                    HashMap<String, String> map1 = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    //altering the
                    map1.put("name", json.getString("name"));
                    String dates =  json.getString("loto_date");
                    //dates= dates.replace("-", "year");
                    dates =  replaceCharAt(dates ,4,"year");
                    dates =  replaceCharAt(dates ,7,"month");
                    dates  = dates+="day";

                    map1.put("info_date",dates);
                    String _titles = json.getString("title");

                     map1.put("title", "("+_titles+")");

                    // adding HashList to ArrayList//
                    arrList.add(map1);
                }


            } catch ( JSONException e) {
                e.printStackTrace();
            }

//我在这里设置数据,但我不知道如何设置图标  当前代码

            ListView mySpinner = (ListView) findViewById(R.id.listviewpo);
            //try the step 5 in here
            if(!arrList.isEmpty()){

                ListAdapter adapter = new SimpleAdapter(InfoListActivity.this, arrList,
                        R.layout.customlistforinfo, new String[] {"name", "title", "info_date"},
                        new int[] {R.id.infoname,R.id.infontitle, R.id.dayk});

                mySpinner.setAdapter(adapter);
            }

1 个答案:

答案 0 :(得分:2)

您必须为列表视图制作自己的自定义适配器才能在列表视图中添加图像。您将要扩展ArrayAdapter。这是我前一段时间写的一些代码,它基本上完全符合您的要求(我认为)。希望这会对你有所帮助。干杯

import java.util.ArrayList;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class StandingsAdapter extends ArrayAdapter<ResidentialCollege>{

  public StandingsAdapter(Context context, ArrayList<ResidentialCollege> colleges) {
    super(context, R.layout.standings_row_layout, colleges);
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent){
    LayoutInflater inflater = LayoutInflater.from(getContext());

    View view = inflater.inflate(R.layout.standings_row_layout, parent, false);

    ResidentialCollege college = (ResidentialCollege) getItem(position);
    TextView collegeView = (TextView) view.findViewById(R.id.standingsTextView);
    collegeView.setText(getDisplayName(college.getName()));

    TextView scoreView = (TextView) view.findViewById(R.id.tyngScore);
    scoreView.setText("" + getDisplayScore(college.getScore()));


    ImageView imageView = (ImageView) view.findViewById(R.id.resCollegeImage);
    imageView.setImageResource(college.getImgResource());

    return view;

  }

  //generate a string to display from a given residential college name to avoid
  //long names messing up the display. E.G Johnathan Edwards
  private String getDisplayName(String name) {
    if(name.length() > 10){
      return (name.substring(0, 7).toUpperCase() + " ...");
    }
    else return name.toUpperCase();
  }

  //to get rid of the .0's at the end of the scores that are integers.
  //Came at the cost of allowing scores to have .5's forcing floating point numbers.
  private String getDisplayScore(Double score){
    if((score % 1) == 0){
      return "" + score.intValue();
    }
    else{
      return "" + score;
    }
  }

  public void updateStandings(ArrayList<ResidentialCollege> newResList) {
      this.clear();
      for(ResidentialCollege res : newResList){
        this.add(res);
      }
      this.notifyDataSetChanged();
  }

  //perform a simple insertion sort(only 12 elements, so should be fast enough)
  public ArrayList<ResidentialCollege> sortByScore(ArrayList<ResidentialCollege> listToSort){
    ArrayList<ResidentialCollege> sorted = new ArrayList<ResidentialCollege>();
    sorted.add(listToSort.get(0));
    listToSort.remove(0);

    for(ResidentialCollege college : listToSort){
      for(int i = 0; i < sorted.size(); i++){
        if(college.getScore() >= sorted.get(i).getScore()){
          sorted.add(i, college);
          Log.d("inserted:", college.getName() + " " + "at position " + i);
          break;
        }
        //add it to the end it has the lowest score seen so far.
        else if(i == (sorted.size() - 1)){
          sorted.add(college);
          Log.d("appended:", college.getName() + " " + "at position" + i);
          break;
        }
      }
    }
    return sorted;
  }
}