在列表视图android的坏形象更新 [英] bad update image in listview android

查看:79
本文介绍了在列表视图android的坏形象更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用这个code的列表视图俗

自定义的ListView

 公共类ListAdapt延伸BaseAdapter {私人活动活动;
私人的ArrayList<&HashMap的LT;字符串,字符串>>数据;
私有静态LayoutInflater吹气= NULL;
公共ImageLoader的ImageLoader的;公共ListAdapt(活动一,ArrayList的<&HashMap的LT;字符串,字符串> D 1和D){
    活性=一个;
    数据= D;
    吹气=(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    ImageLoader的=新ImageLoader的(activity.getApplicationContext());
}公众诠释的getCount(){
    返回data.size();
}公共对象的getItem(INT位置){
    返回的位置;
}众长getItemId(INT位置){
    返回的位置;
}公共查看getView(INT位置,查看convertView,父母的ViewGroup){
    查看VI = convertView;
    如果(convertView == NULL)
        VI = inflater.inflate(R.layout.list_item,NULL);    TextView的标题=(TextView中)vi.findViewById(R.id.name); //称号
    TextView的TITLE1 =(TextView中)vi.findViewById(R.id.name1);
    TextView的标题2 =(TextView中)vi.findViewById(R.id.idi);
    HashMap的<字符串,字符串>歌=新的HashMap<字符串,字符串>();
    曲= data.get(位置);    //设置列表视图中的所有值
    title.setText(song.get(online.KEY_NAME));
    title2.setText(song.get(online.KEY_ID));
    title1.setText(song.get(online.KEY_DESC));
    。字符串= title1.getText()的toString();    新DownloadImageTask((ImageView的)vi.findViewById(R.id.imageView1))
    .execute(如);    返回VI;
}
私有类DownloadImageTask扩展的AsyncTask<弦乐,太虚,位图> {
      ImageView的bmImage;      公共DownloadImageTask(ImageView的bmImage){
          this.bmImage = bmImage;
      }      保护位图doInBackground(字符串的URL ...){
          字符串urldisplay =网址[0];
          位图mIcon11 = NULL;
          尝试{
            在的InputStream =新的java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.de codeStream(中);
          }赶上(例外五){
              Log.e(错误,e.getMessage());
              e.printStackTrace();
          }
          返回mIcon11;
      }      保护无效onPostExecute(位图结果){
          bmImage.setImageBitmap(结果);
      }
    }
}

在自定义列表视图中的AsyncTask使用的AsyncTask,加载图像从URL。

URL =字符串为

这code工作和负载的图像,但是当触摸滚动在手机,混乱列表视图图像。

ListActivity

 公共类的在线扩展ListActivity {私人ProgressDialog pDialog;
//所有静态变量
    静态最终字符串URL =htt​​p://titanz13.byethost10.com/$c$ce.xml;
    // XML节点键
    静态最后弦乐KEY_ITEM =项; //父节点
    静态最后弦乐KEY_ID =ID;
    静态最后弦乐KEY_NAME =名;    静态最后弦乐KEY_DESC =说明;    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        requestWindowFeature(Window.FEATURE_NO_TITLE);           setTheme(android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
           。getWindow()addFlags(WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER);
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.online);        新GetContacts()执行();        //选择单个ListView项
        ListView控件LV = getListView();        lv.setOnItemClickListener(新OnItemClickListener(){            @覆盖
            公共无效onItemClick(适配器视图<>母公司,观景,
                    INT位置,长的id){                字符串名称=((的TextView)view.findViewById                        (R.id.name))的getText()的toString()。
                串H =((的TextView)view.findViewById                        (R.id.idi))的getText()的toString()。
                 INT myNum的=的Integer.parseInt(H);                 如果(myNum的== 1){                     URI URI = Uri.parse(名);
                        意向意图=新意图(Intent.ACTION_VIEW,URI);
                        startActivity(意向);                 }其他{                意图whatsappIntent =新意图(Intent.ACTION_SEND);
                whatsappIntent.setType(text / plain的);
                whatsappIntent.setPackage(com.whatsapp);                whatsappIntent.putExtra(Intent.EXTRA_TEXT,名);
                尝试{
                    startActivity(whatsappIntent);
                }赶上(android.content.ActivityNotFoundException前){
                    上下文的背景下= getApplicationContext();
                    CharSequence的文字=نرمافزارواتساپبررویدستگاهشمانصبنیست
                    INT持续时间= Toast.LENGTH_LONG;                    吐司面包= Toast.makeText(背景,文本,持续时间);
                    toast.show();
                }
                 }            }
        });
    }    私有类GetContacts扩展的AsyncTask<太虚,太虚,太虚> {
        ArrayList的<&HashMap的LT;字符串,字符串>>菜单项=新的ArrayList<&HashMap的LT;字符串,字符串>>();
        @覆盖
        在preExecute保护无效(){
            super.on preExecute();
            //显示进度对话框
            pDialog =新ProgressDialog(online.this);
            pDialog.setMessage(请稍候...);
            pDialog.setCancelable(假);
            pDialog.show();        }        @覆盖
        保护无效doInBackground(虚空......为arg0){            XMLParser的解析器=新XMLParser的();
            字符串XML = parser.getXmlFromUrl(URL); //获取XML
            文档的文档= parser.getDomElement(XML); //获得DOM元素            节点列表NL = doc.getElementsByTagName(KEY_ITEM);
            项目> //遍历所有项目节点&LT循环;
            的for(int i = 0; I< nl.getLength();我++){
                //创建新的HashMap
                HashMap的<字符串,字符串>地图=新的HashMap<字符串,字符串>();
                元素e =(元)nl.item(I)
                //将每个子节点的HashMap键=>值
                map.put(KEY_ID,parser.getValue(即KEY_ID));
                map.put(KEY_NAME,parser.getValue(即KEY_NAME));                map.put(KEY_DESC,parser.getValue(即KEY_DESC));                //添加HashList到ArrayList的
                menuItems.add(地图);
            }
            //添加菜单项到ListView控件
            返回null;
        }        @覆盖
        保护无效onPostExecute(虚空结果){
            super.onPostExecute(结果);
            //辞退进度对话框
            如果(pDialog.isShowing())
                pDialog.dismiss();            ListAdapt适配器=新ListAdapt(online.this,菜单项);            setListAdapter(适配器);        }    }


解决方案

由于你是如下不好的做法,远程URL /图片加载到里面的ListView的ImageView这是杂乱。

您需要按照最佳做法,以图像加载到里面的ListView ImageView的。一个最佳实践是实施图片的延迟加载逻辑。使用该图像会在后台加载和缓存到内存中,这样它会从缓存中加载图像,而不是重新下载。

有具有相同的实现在Web上提供许多图书馆,我已经写了一些图书馆的一个帖子:<一href=\"http://www.technotalkative.com/lazy-productive-android-developer-part-5-image-loading-library/\"相对=nofollow>图像加载库

(P.S。对不起,放置一个链接里面的答案,因为我不能包括从原来的链路所需的部分,因为它是冗长,对不起,包括个人博客链接,但都能在这里找到所需的参考。)

i use this code for a custum listview

Custom ListView

public class ListAdapt extends BaseAdapter {

private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader; 

public ListAdapt(Activity a, ArrayList<HashMap<String, String>> d) {
    activity = a;
    data=d;
    inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    imageLoader=new ImageLoader(activity.getApplicationContext());
}

public int getCount() {
    return data.size();
}

public Object getItem(int position) {
    return position;
}

public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
    View vi=convertView;
    if(convertView==null)
        vi = inflater.inflate(R.layout.list_item, null);

    TextView title = (TextView)vi.findViewById(R.id.name); // title
    TextView title1 = (TextView)vi.findViewById(R.id.name1);
    TextView title2 = (TextView)vi.findViewById(R.id.idi);


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

    // Setting all values in listview
    title.setText(song.get(online.KEY_NAME));
    title2.setText(song.get(online.KEY_ID));
    title1.setText(song.get(online.KEY_DESC));
    String as = title1.getText().toString();

    new DownloadImageTask((ImageView) vi.findViewById(R.id.imageView1))
    .execute(as);



    return vi;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
      ImageView bmImage;

      public DownloadImageTask(ImageView bmImage) {
          this.bmImage = bmImage;
      }

      protected Bitmap doInBackground(String... urls) {
          String urldisplay = urls[0];
          Bitmap mIcon11 = null;
          try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
          } catch (Exception e) {
              Log.e("Error", e.getMessage());
              e.printStackTrace();
          }
          return mIcon11;
      }

      protected void onPostExecute(Bitmap result) {
          bmImage.setImageBitmap(result);
      }
    }
}

in custom listview use a Asynctask , load image from URL in Asynctask .

URL = String is

this code work and load image but when touch scroll in phone , Cluttered listview image .

ListActivity

public class online extends ListActivity {

private ProgressDialog pDialog;
// All static variables
    static final String URL = "http://titanz13.byethost10.com/codee.xml";
    // XML node keys
    static final String KEY_ITEM = "item"; // parent node
    static final String KEY_ID = "id";
    static final String KEY_NAME = "name";

    static final String KEY_DESC = "description";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);

           setTheme(android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
           getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.online);



        new GetContacts().execute();





        // selecting single ListView item
        ListView lv = getListView();

        lv.setOnItemClickListener(new OnItemClickListener() {

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

                String name = ((TextView) view.findViewById

                        (R.id.name)).getText().toString();
                String h = ((TextView) view.findViewById

                        (R.id.idi)).getText().toString();
                 int mynum = Integer.parseInt(h);

                 if (mynum==1){

                     Uri uri = Uri.parse(name); 
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri); 
                        startActivity(intent);

                 }else {



                Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
                whatsappIntent.setType("text/plain");
                whatsappIntent.setPackage("com.whatsapp");

                whatsappIntent.putExtra(Intent.EXTRA_TEXT, name);
                try {
                    startActivity(whatsappIntent);
                } catch (android.content.ActivityNotFoundException ex) {
                    Context context = getApplicationContext();
                    CharSequence text = "نرم افزار واتس اپ بر روی دستگاه شما نصب نیست";
                    int duration = Toast.LENGTH_LONG;

                    Toast toast = Toast.makeText(context, text, duration);
                    toast.show();
                }   
                 }

            }
        });
    }









    private class GetContacts extends AsyncTask<Void, Void, Void> {
        ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(online.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {



            XMLParser parser = new XMLParser();
            String xml = parser.getXmlFromUrl(URL); // getting XML
            Document doc = parser.getDomElement(xml); // getting DOM element

            NodeList nl = doc.getElementsByTagName(KEY_ITEM);
            // looping through all item nodes <item>
            for (int i = 0; i < nl.getLength(); i++) {
                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();
                Element e = (Element) nl.item(i);
                // adding each child node to HashMap key => value
                map.put(KEY_ID, parser.getValue(e, KEY_ID));
                map.put(KEY_NAME, parser.getValue(e, KEY_NAME));

                map.put(KEY_DESC, parser.getValue(e, KEY_DESC));

                // adding HashList to ArrayList
                menuItems.add(map);
            }
            // Adding menuItems to ListView


            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();

            ListAdapt adapter = new ListAdapt(online.this, menuItems);

            setListAdapter(adapter);



        }

    }

解决方案

It's cluttered because you are following a bad practice to load remote URLs/Images into ImageView inside ListView.

You need to follow the best practices to load Image into ImageView inside ListView. One best practice is to implement lazy loading of images logic. Using which images would be loaded in background and cached into the memory so that it would load images from cache rather than downloading it again.

There are many libraries available on the web with the same implementation, I have written a post on some of the libraries: Image loading library

(P.S. Sorry for placing a link inside answer as I can't include required parts from the original link because it's lengthy and Sorry for including a personal blog link but it's required here for the reference.)

这篇关于在列表视图android的坏形象更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆