Listview太慢了,我无法解决这个问题

时间:2018-11-04 23:16:56

标签: java android

我有一个列表视图,其中为列表中的每个项目分配一个图像视图。 事实是,我已经做到了该应用程序一次只能加载10行,并且在用户滚动时会添加项,启用硬件加速,将图片压缩并调整为很小的尺寸,但是无论我执行listview仍然很落后。

我试图在线查找,但我不知道如何在我的场景中实现任何东西,或者其他任何可以加速该过程的东西。 这是我的BaseAdapter:

  public View getView(int position, View convertView, ViewGroup parent) {

    LayoutInflater layoutInflater = ((Activity)context).getLayoutInflater();
    View view = layoutInflater.inflate(R.layout.library_layout, parent, false);
    view.setBackgroundColor(Color.parseColor("#FFFFFF"));
    final GamesLibrary gl = objects.get(position);
    TextView title = (TextView)view.findViewById(R.id.titleId);
    TextView excerpt = (TextView)view.findViewById(R.id.excerptId);
    ImageView imageView = view.findViewById(R.id.listViewImageView);
    ImageButton commBt = view.findViewById(R.id.goToCommLv);
    final TextView author = view.findViewById(R.id.authorId);
    final CheckBox likeBox = view.findViewById(R.id.likeIconLv);
    ImageButton sharingButton = view.findViewById(R.id.shareButtonLv);
    final SharedPreferences sp;
    sp=context.getSharedPreferences("likes", 0);
    final SharedPreferences.Editor editor = sp.edit();
    String[] allFavsIds =SpIdstoArr(sp.getString("ids", ""));
    final String id = String.valueOf(gl.getId());
    SharedPreferences sp4 =context.getSharedPreferences("LocalLogInData", 0);
    String uname= sp4.getString("Uname","dsufhsiudhfsdef");

    if(gl.getTitle().contains(uname))
    {
        Log.d("aw12","aw12");
        commBt.setClickable(false);
        commBt.setEnabled(false);
        commBt.setAlpha(0.5f);
    }






    title.setText(gl.getTitle());
    Log.d("glgl",gl.getTitle());
    excerpt.setText(gl.getExcerpt());
    author.setText("by " + gl.getAuthor());
    String FirstTag = "";
    try {
        FirstTag = gl.getTags()[0];
    }
    catch (Exception e)
    {
        Log.d("gameLibAdap", e.toString());}
    if(FirstTag != null) {
        if (FirstTag.equals("מערך אכפתיות"))
            imageView.setImageDrawable(context.getApplicationContext().getResources().getDrawable(R.drawable.care));
        else if (FirstTag.equals("מערך חגים"))
            imageView.setImageDrawable(context.getApplicationContext().getResources().getDrawable(R.drawable.holidays));
        else if (FirstTag.equals("מערך חשיבה אחרת"))
            imageView.setImageDrawable(context.getApplicationContext().getResources().getDrawable(R.drawable.thinkdifferent2));
        else if (FirstTag.equals("מערך גיבוש והנאה"))
            imageView.setImageDrawable(context.getApplicationContext().getResources().getDrawable(R.drawable.fun));
        else if (FirstTag.equals("מערך חברות"))
            imageView.setImageDrawable(context.getApplicationContext().getResources().getDrawable(R.drawable.friendship));
        else if (FirstTag.equals("מערך סובלנות"))
            imageView.setImageDrawable(context.getApplicationContext().getResources().getDrawable(R.drawable.tolerance));
        else if (FirstTag.equals("מערך אחריות"))
            imageView.setImageDrawable(context.getApplicationContext().getResources().getDrawable(R.drawable.responsibility));
        else if (FirstTag.equals("פעולות ללא מערך"))
            imageView.setImageDrawable(context.getApplicationContext().getResources().getDrawable(R.drawable.logo1));
        else if (FirstTag.equals("מערך שיתוף פעולה"))
            imageView.setImageDrawable(context.getApplicationContext().getResources().getDrawable(R.drawable.teamwork));
        else if (FirstTag.equals("מערך חוץ וטבע"))
            imageView.setImageDrawable(context.getApplicationContext().getResources().getDrawable(R.drawable.nature));
        else if (FirstTag.equals("מערך מנהיגות"))
            imageView.setImageDrawable(context.getApplicationContext().getResources().getDrawable(R.drawable.leading));
        else if (FirstTag.equals("מערך סבלנות"))
            imageView.setImageDrawable(context.getApplicationContext().getResources().getDrawable(R.drawable.patience));
        else if (FirstTag.equals("מערך יוזמה"))
            imageView.setImageDrawable(context.getApplicationContext().getResources().getDrawable(R.drawable.yozma));
        else if (FirstTag.equals("מערך שוויון"))
            imageView.setImageDrawable(context.getApplicationContext().getResources().getDrawable(R.drawable.equlity));
        else if (FirstTag.equals("מערך הישגים אישיים"))
            imageView.setImageDrawable(context.getApplicationContext().getResources().getDrawable(R.drawable.personalachivements));
        else if (FirstTag.equals("מערך עידן מודרני"))
            imageView.setImageDrawable(context.getApplicationContext().getResources().getDrawable(R.drawable.modern));
        else if (FirstTag.equals("ערך שוויון"))
            imageView.setImageDrawable(context.getApplicationContext().getResources().getDrawable(R.drawable.equlity));
        else if (FirstTag.equals("ערך ישראליות/ ציונות"))
            imageView.setImageDrawable(context.getApplicationContext().getResources().getDrawable(R.drawable.zionism));
        else if (FirstTag.equals("מערך מודעות"))
            imageView.setImageDrawable(context.getApplicationContext().getResources().getDrawable(R.drawable.awareness2));
        else if (FirstTag.equals("מערך חשיבה אחרת"))
            imageView.setImageDrawable(context.getApplicationContext().getResources().getDrawable(R.drawable.thinkdifferent2));
        else if (FirstTag.equals("מערך הישגים אישיים"))
            imageView.setImageDrawable(context.getApplicationContext().getResources().getDrawable(R.drawable.personalachivements));
        else if (FirstTag.equals("ערך קבלת השונה"))
            imageView.setImageDrawable(context.getApplicationContext().getResources().getDrawable(R.drawable.acceptance));
        else if (FirstTag.equals("אלכוהול וסמים"))
            imageView.setImageDrawable(context.getApplicationContext().getResources().getDrawable(R.drawable.alcohol));
        else if (FirstTag.equals("ללא הכנה מראש"))
            imageView.setImageDrawable(context.getApplicationContext().getResources().getDrawable(R.drawable.unprepared));
        else if (FirstTag.equals("מערך היכרות"))
            imageView.setImageDrawable(context.getApplicationContext().getResources().getDrawable(R.drawable.meeting));
        else if (FirstTag.equals("מערך הדרכה"))
            imageView.setImageDrawable(context.getApplicationContext().getResources().getDrawable(R.drawable.guiding));
        else if (FirstTag.equals("מערך יום הזיכרון"))
            imageView.setImageDrawable(context.getApplicationContext().getResources().getDrawable(R.drawable.memorial));
        else if (FirstTag.equals("מערך יום הזיכרון לשואה"))
            imageView.setImageDrawable(context.getApplicationContext().getResources().getDrawable(R.drawable.holocaustmemorial));
        else if (FirstTag.equals("מערך שינוי"))
            imageView.setImageDrawable(context.getApplicationContext().getResources().getDrawable(R.drawable.change));
        else
            imageView.setImageDrawable(context.getApplicationContext().getResources().getDrawable(R.drawable.logo1));

    }


    likeBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView,boolean isChecked)
        {

            if(isChecked)
            {
                String value = sp.getString("ids", "");
                Log.d("ids", value);
                value += "," + id + "/";
                editor.putString("ids", value).commit();
                Log.d("ids", value);
                Log.d("ids", sp.getString("ids", ""));
            }
            if(!isChecked)
            {
                String value = sp.getString("ids", "");
                String replaceString= value.replace("," + id + "/", "");
                editor.putString("ids", replaceString).commit();
                Log.d("ids2", sp.getString("ids", ""));
            }
            Log.d("ids3", sp.getString("ids", ""));

        }
    });
    if (checkMatch(String.valueOf(id),allFavsIds))
        likeBox.setChecked(true);
    else
        likeBox.setChecked(false);

    commBt.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent in = new Intent(context,CommentActivity.class);
            in.putExtra("Json", gl.getCommJson());
            in.putExtra("pId", String.valueOf(id));
            in.putExtra("cats", gl.getCategories());
            context.startActivity(in);
        }
    });



    sharingButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            shareIt(gl.getUrl(),gl.getTitle());
        }
    });






    return view;}

我将进行解释,因此我的代码不会引起混淆,我只是通过其属性为每个项目分配文本和图像视图,还有一个“喜欢”按钮和一个“注释”按钮,可将用户带到注释页面。你们对我该怎么办知道吗?

我是初学者。

更新:支票匹配代码:

public static boolean checkMatch(String id, String[] favIds)
{
    boolean b = false;
    for (int i = 0; i <favIds.length; i++)
    {
        if(favIds[i].equals(id)) {
            b = true;
            favIds[i] = "";
        }
    }
    return b;
}

新代码-ViewHlder:

class MyviewHolder
{
    TextView title, excerpt,author;
    ImageView imageView, profilepic;
    ImageButton commBt,sharingButton;
    CheckBox likeBox;
    MyviewHolder(View v)
    {
         title = (TextView)v.findViewById(R.id.titleId);
         excerpt = (TextView)v.findViewById(R.id.excerptId);
         imageView =(ImageView) v.findViewById(R.id.listViewImageView);
         commBt = (ImageButton) v.findViewById(R.id.goToCommLv);
          author =(TextView) v.findViewById(R.id.authorId);
          likeBox = (CheckBox) v.findViewById(R.id.likeIconLv);
         sharingButton = (ImageButton) v.findViewById(R.id.shareButtonLv);
         profilepic = v.findViewById(R.id.saProfilePic);
         profilepic.setVisibility(View.VISIBLE);
    }

}

新代码-getView:

@Override
public View getView(int position, View convertView, ViewGroup parent)
{



    View view =convertView;
    MyviewHolder viewHolder=null;

    if(view==null)
    {
        LayoutInflater layoutInflater = ((Activity)context).getLayoutInflater();
        view = layoutInflater.inflate(R.layout.library_layout, parent, false);
        viewHolder=new MyviewHolder(view);
        view.setTag(viewHolder);
        Log.d("gg22","creating");
        view.setBackgroundColor(Color.parseColor("#FFFFFF"));
    }
    else
    {
        viewHolder = (MyviewHolder) view.getTag();
        Log.d("gg22","recycling");
    }



    final GamesLibrary gl = objects.get(position);

    viewHolder.title.setText(gl.getTitle());
    viewHolder.excerpt.setText(gl.getExcerpt());
    viewHolder.imageView.setImageResource(R.drawable.logo1);
    viewHolder.author.setText("by " + gl.getAuthor());



    final SharedPreferences sp;
    sp=context.getSharedPreferences("likes", 0);
    final SharedPreferences.Editor editor = sp.edit();
    String[] allFavsIds =SpIdstoArr(sp.getString("ids", ""));
    final String id = String.valueOf(gl.getId());

    if(gl.getTitle().contains(UName()))
    {
        viewHolder.commBt.setClickable(false);
        viewHolder.commBt.setEnabled(false);
        viewHolder.commBt.setAlpha(0.5f);
    }


    int imageviewRID;






    String FirstTag = "";
    try {
        FirstTag = gl.getTags()[0];
    }
    catch (Exception e)
    {
        Log.d("gameLibAdap", e.toString());}

    if(FirstTag != null) {
        if (FirstTag.equals("מערך אכפתיות"))
            imageviewRID=R.drawable.care;
        else if (FirstTag.equals("מערך חגים"))
            imageviewRID=R.drawable.holidays;
        else if (FirstTag.equals("מערך חשיבה אחרת"))
            imageviewRID=R.drawable.thinkdifferent2;
        else if (FirstTag.equals("מערך גיבוש והנאה"))
            imageviewRID=R.drawable.fun;
        else if (FirstTag.equals("מערך חברות"))
            imageviewRID=R.drawable.friendship;
        else if (FirstTag.equals("מערך סובלנות"))
            imageviewRID=R.drawable.tolerance;
        else if (FirstTag.equals("מערך אחריות"))
            imageviewRID=R.drawable.responsibility;
        else if (FirstTag.equals("פעולות ללא מערך"))
            imageviewRID=R.drawable.logo1;
        else if (FirstTag.equals("מערך שיתוף פעולה"))
            imageviewRID=R.drawable.teamwork;
        else if (FirstTag.equals("מערך חוץ וטבע"))
            imageviewRID=R.drawable.nature;
        else if (FirstTag.equals("מערך מנהיגות"))
            imageviewRID=R.drawable.leading;
        else if (FirstTag.equals("מערך סבלנות"))
            imageviewRID=R.drawable.patience;
        else if (FirstTag.equals("מערך יוזמה"))
            imageviewRID=R.drawable.yozma;
        else if (FirstTag.equals("מערך שוויון"))
            imageviewRID=R.drawable.equlity;
        else if (FirstTag.equals("מערך הישגים אישיים"))
            imageviewRID=R.drawable.personalachivements;
        else if (FirstTag.equals("מערך עידן מודרני"))
            imageviewRID=R.drawable.modern;
        else if (FirstTag.equals("ערך שוויון"))
            imageviewRID=R.drawable.equlity;
        else if (FirstTag.equals("ערך ישראליות/ ציונות"))
            imageviewRID=R.drawable.zionism;
        else if (FirstTag.equals("מערך מודעות"))
            imageviewRID=R.drawable.awareness2;
        else if (FirstTag.equals("מערך חשיבה אחרת"))
            imageviewRID=R.drawable.thinkdifferent2;
        else if (FirstTag.equals("מערך הישגים אישיים"))
            imageviewRID=R.drawable.personalachivements;
        else if (FirstTag.equals("ערך קבלת השונה"))
            imageviewRID=R.drawable.acceptance;
        else if (FirstTag.equals("אלכוהול וסמים"))
            imageviewRID=R.drawable.alcohol;
        else if (FirstTag.equals("ללא הכנה מראש"))
            imageviewRID=R.drawable.unprepared;
        else if (FirstTag.equals("מערך היכרות"))
            imageviewRID=R.drawable.meeting;
        else if (FirstTag.equals("מערך הדרכה"))
            imageviewRID=R.drawable.guiding;
        else if (FirstTag.equals("מערך יום הזיכרון"))
            imageviewRID=R.drawable.memorial;
        else if (FirstTag.equals("מערך יום הזיכרון לשואה"))
            imageviewRID=R.drawable.holocaustmemorial;
        else if (FirstTag.equals("מערך שינוי"))
            imageviewRID=R.drawable.change;
        else
            imageviewRID=R.drawable.logo1;
        viewHolder.imageView.setImageResource(imageviewRID);
    }


    viewHolder.likeBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView,boolean isChecked)
        {

            if(isChecked)
            {
                String value = sp.getString("ids", "");
                Log.d("ids", value);
                value += "," + id + "/";
                editor.putString("ids", value).apply();
                Log.d("ids", value);
                Log.d("ids", sp.getString("ids", ""));
            }
            if(!isChecked)
            {
                String value = sp.getString("ids", "");
                String replaceString= value.replace("," + id + "/", "");
                editor.putString("ids", replaceString).apply();
                Log.d("ids2", sp.getString("ids", ""));
            }
            Log.d("ids3", sp.getString("ids", ""));

        }
    });
    if (checkMatch(String.valueOf(id),allFavsIds))
        viewHolder.likeBox.setChecked(true);
    else
        viewHolder.likeBox.setChecked(false);

    viewHolder.commBt.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent in = new Intent(context,CommentActivity.class);
            in.putExtra("Json", gl.getCommJson());
            in.putExtra("pId", String.valueOf(id));
            in.putExtra("cats", gl.getCategories());
            context.startActivity(in);
        }
    });



    viewHolder.sharingButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            shareIt(gl.getUrl(),gl.getTitle());
        }
    });






    return view;
}

3 个答案:

答案 0 :(得分:1)

这可以通过 View Holder模式进行改进。不必为每个项目添加新视图并进行所有样板设置,而可以对以前在可见区域之外的项目重新使用以前创建的视图。

请注意,已经回答了几次。看看以下问题和答案:

我将进行其他更改以提高性能:

  • 删除对“正常”行为的异常使用。通常,代码会针对非异常流(需要引用)进行优化,因此碰到catch块通常可能是一个问题。
  • SharedPreferences.Editor.commit()切换到SharedPreferences.Editor.apply()。根据文档commit()同步写入磁盘,而apply()仅写入内存结构并异步写入磁盘。这里的问题可能是您首先创建了侦听器,然后调用了setChecked。检查在调用setChecked时是否调用了侦听器,并在代码中切换侦听器和setChecked的创建。
  • 查看长if ... else ... if是否存在问题。尝试地图。
  • 请勿为每个新项目创建新的侦听器。每个ViewHolder创建一次,将gl上的ViewHolder项设置为字段,并在侦听器中引用该字段。

如果想花哨的话,请使用Android Profiler来衡量该方法的性能,并了解您大部分时间在哪里度过。

答案 1 :(得分:1)

您应该使用ViewHolder link

在item_listview.xml中,如果已设置imageview的背景,请将其删除

答案 2 :(得分:0)

正如迈克尔·布彻(Michael Butscher)所述,您绝对应该研究GamesLibrary类。如果是您自己,则可以通过将长时间运行的任务移至后台线程而不是使用UI线程来进行很多改进。

除了我想给你一些代码风格的提示。

  1. 如果使用块,则可以使用开关块而不是其他所有块。这将大大缩短您的代码并使其更具可读性。
  2. 对于您经常使用且不变的字符串或其他值,请使用常量。 (例如,您所有的SharedPreferences键),当您必须更改其中一些值时,这将使您省去很多工作。
  3. 您还应该在getSharedPreferences()中使用提供的常量,例如Context.MODE_PRIVATE。代码清晰易读。