Добавьте ImageView с AQUERY в ListView

У меня есть рабочий список с текстом, и теперь я хочу добавить изображение с помощью AQuery.

Я изменил XML и добавил элемент ImageView, и теперь хочу добавить загрузку изображения с помощью AQuery. До сих пор я использовал SpecialAdapter для TextViews, но я изо всех сил пытаюсь получить изображение.

мой код до сих пор, я думаю, что теперь мне нужно что-то сделать с адаптером, например

aq.id(R.id.imageView).image(c.getString("URL"), false, false);

, а что именно?

package com.schatten.p5_4;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

public class GetArticleList extends Activity {
public final static String EXTRA_MESSAGE = ".MESSAGE";
    //JSON Node Names
    private static final String TABLE = "Table";
    private static final String A_ID = "AID";
    private static final String A_TEXT = "ArtikelText";
    private static final String A_GROUP = "Fuel";
    private static final String A_PRICE = "Preis_qm";
    private static final String A_IMG_URL = "URL";
    private static String url = "";
    ListView lv;
    TextView aid;
    TextView articletext;
    TextView preis_qm;
    ImageView article_img;
    ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
    JSONArray android = null;
    private Context context;
    private AQuery aq;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.article_list);
    oslist = new ArrayList<HashMap<String, String>>();

    Intent intent = getIntent();
    url = GlobalDataPool.urlArticleList + intent.getStringExtra(GetArticle.EXTRA_MESSAGE);

    new JSONParse().execute();
}

private class JSONParse extends AsyncTask<String, String, JSONObject> {
    private ProgressDialog pDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        aid = (TextView) findViewById(R.id.tv_aid);
        preis_qm = (TextView) findViewById(R.id.tv_preis_qm);
        articletext = (TextView) findViewById(R.id.tv_articletext);
        article_img = (ImageView) findViewById((R.id.list_image);
        pDialog = new ProgressDialog(GetArticleList.this);
        pDialog.setMessage("Getting Data ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected JSONObject doInBackground(String... args) {
        JSONParser2 jParser = new JSONParser2();
        // Getting JSON from URL
        JSONObject json = jParser.getJSONFromUrl(url);
        return json;
    }

    @Override
    protected void onPostExecute(JSONObject json) {
        pDialog.dismiss();
        try {
            // Getting JSON Array from URL
            android = json.getJSONArray(TABLE);
            for (int i = 0; i < android.length(); i++) {

                JSONObject c = android.getJSONObject(i);
                // Storing  JSON item in a Variable
                String AID = c.getString(A_ID);
                String ATEXT = c.getString(A_TEXT);
                String APRICE = c.getString(A_PRICE);
                String AIMGURL = GlobalDataPool.imageURL + c.getString("URL");
                // Adding value HashMap key => value
                HashMap<String, String> map = new HashMap<String, String>();
                map.put(A_ID, AID);
                map.put(A_TEXT, ATEXT);
                map.put(A_PRICE, APRICE);
                map.put(A_IMG_URL, AIMGURL);
                oslist.add(map);
                lv = (ListView) findViewById(R.id.list);
                SpecialAdapter adapter = new SpecialAdapter(GetArticleList.this, oslist,
                        R.layout.article_list_v,
                        new String[]{A_ID, A_TEXT, A_PRICE, A_IMG_URL}, new int[]{
                        R.id.tv_aid, R.id.tv_articletext, R.id.tv_preis_qm, R.id.iv_url});


                lv.setAdapter(adapter);


                lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                              @Override
                                              public void onItemClick(AdapterView<?> parent, View view,
                                                                      int position, long id) {
                                                  //Toast.makeText(GetArticleList.this, "You Clicked at " + oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();

                                                  Intent intent = new Intent(GetArticleList.this, GetArticle.class);
                                                  intent.putExtra(EXTRA_MESSAGE, GlobalDataPool.urlArticle + oslist.get(+position).get("AID"));
                                                  startActivity(intent);
                                                  finish();
                                              }
                                          }
                );
            }
        } catch (JSONException e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "ERROR: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
  }
}

Обновление: К сожалению, я не понял вопроса о моем текущем SpecialAdapter, вот он, и я думаю, что мне нужно управлять загрузкой изображений с помощью AQuery. Но может ли кто-нибудь помочь мне там, пожалуйста?

package com.schatten.p5_4;

import java.util.HashMap;
import java.util.List;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SimpleAdapter;

public class SpecialAdapter extends SimpleAdapter {
private int[] colors = new int[] {0x30FFFFFF, 0x30DDDDDD  };

public SpecialAdapter(Context context, List<HashMap<String, String>> items, int resource, String[] from, int[] to) {
    super(context, items, resource, from, to);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = super.getView(position, convertView, parent);
    int colorPos = position % colors.length;
    view.setBackgroundColor(colors[colorPos]);

    return view;
}
}

person Alex S.    schedule 09.10.2014    source источник


Ответы (2)


Вы должны установить AQuery в методе getView() вашего адаптера. Можете ли вы добавить код вашего адаптера?

person Forin    schedule 09.10.2014
comment
Все, что у меня есть, это определенный адаптер, который, как вы видите, определен с помощью адаптера SpecialAdapter... Итак, что мне там делать? - person Alex S.; 09.10.2014
comment
Вы должны создать свой адаптер, расширяющий BaseAdapter. И затем в методе getView() вы должны использовать AQuery. Вот пример создания собственного адаптера: stackoverflow.com/questions/11258675/ - person Forin; 09.10.2014
comment
Но нет ли способа получить фактический ImageView в SpecialAdapter, а затем напрямую работать с этой ссылкой в ​​AQuery. Создание дополнительного getView для этого состояния звучит очень сложно. - person Alex S.; 09.10.2014

Хорошо, я исправил это с помощью приведенного ниже адаптера, и он работает. Было бы неплохо получить комментарии для лучшего кодирования, я не уверен, что мне нужно делать все, что нужно в разделе getView.

package com.schatten.p5_4;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.androidquery.AQuery;

import java.util.HashMap;
import java.util.List;

public class SpecialAdapter extends SimpleAdapter {
//HashMap<String, String> map = new HashMap<String, String>();
private int[] colors = new int[]{0x30FFFFFF, 0x30DDDDDD};
private List<HashMap<String, String>> data;

public SpecialAdapter(Context context, List<HashMap<String, String>> items, int resource, String[] from, int[] to) {
    super(context, items, resource, from, to);
    data = items;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = super.getView(position, convertView, parent);
    ImageView list_image;
    TextView aid;
    TextView articletext;
    TextView preis_qm;

    if (convertView == null) {
        LayoutInflater mInflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = mInflater.inflate(R.layout.article_list_v, parent, false);
    }

    HashMap<String, String> myitem = new HashMap<String, String>();
    myitem = data.get(position);

    aid = (TextView) convertView.findViewById(R.id.tv_aid);
    preis_qm = (TextView) convertView.findViewById(R.id.tv_preis_qm);
    articletext = (TextView) convertView.findViewById(R.id.tv_articletext);
    aid.setText(myitem.get("AID"));
    articletext.setText(myitem.get("ArtikelText"));
    preis_qm.setText(myitem.get("Preis_qm"));

    String myUrl = myitem.get("URL");

    if (myUrl.toLowerCase().contains("jpg")) {
        list_image = (ImageView) convertView.findViewById(R.id.list_image);
        AQuery aq = new AQuery(convertView);
        aq.id(list_image).image(myitem.get("URL"), false, false, 200, 0);
    }

    return convertView;
}

}

person Alex S.    schedule 14.10.2014