1

嗨,我有来自 Web 服务的数据和图像。使用 AsynTask 获取所有数据,还使用惰性加载器类获取图像,并在列表视图中显示该数据。在初始屏幕之后,主屏幕数据显示在列表视图中。
但是在列表视图中滚动时出现了一些问题,它运行不顺畅是口吃。

我的适配器 java 文件

public class NewsScreenAdapter extends BaseAdapter implements OnTouchListener,Handler.Callback {

    LayoutInflater inflater;
   // public GifDecoderView webview1;
    public static  viewholder holder;
    View view = null;
    public Context context;
    public ImageLoader IL;
    public String imgUrl;
    public static String addurl;    
    public Activity activity;
    String image;
    public static String str;
    public static Date parsed;
    public static String ac, cat_id;

    private WebViewClient client;



    public NewsScreenAdapter(NewsScreenActivity a) {
        // TODO Auto-generated constructor stub

        this.context = a.getApplicationContext();
        this.activity = a;       
        inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        IL = new ImageLoader(activity.getApplicationContext());   
     }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        // return NewsScreenActivity.arrayList_header.size();

        return NewsScreenActivity.TotalDataArray.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }


    @Override
    public int getItemViewType(int position) {
        // TODO Auto-generated method stub
        return position;
    }
    @Override
    public int getViewTypeCount() {
        // TODO Auto-generated method stub
        return NewsScreenActivity.TotalDataArray.size();
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }


    public View getView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub

        View vi = convertView;

            holder = new viewholder();

            vi = inflater.inflate(R.layout.newsscren_row, null);
            holder.news_header_title = (TextView) vi.findViewById(R.id.header_title);
            holder.ll_data = (LinearLayout) vi.findViewById(R.id.data);

            vi.setTag(holder);

            // ------- set custom Font----- 
            Typeface typefont=Typeface.createFromAsset(context.getAssets(),"Times New Roman.ttf");
            holder.news_header_title.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                cat_id = NewsScreenActivity.arrayList_header.get(position);
                ac = ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray.get(position)).catId;

                activity.startActivity(new Intent(activity,CategoryActivity.class).putExtra("id", ac));

            }
        });

        holder.ll_data.removeAllViews();
      //  try {

              int  storyLenght = ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray.get(position)).storyArr.size();

       /* } catch (Exception e) {
            // TODO: handle exception
        }*/


        for (int i = 0; i < storyLenght; i++) {

            view = LayoutInflater.from(activity).inflate(R.layout.sub_row, null);

            holder.short_text = (TextView) view.findViewById(R.id.short_text);
            holder.image = (ImageView) view.findViewById(R.id.image);
            holder.des = (TextView) view.findViewById(R.id.des);
            holder.date_time = (TextView) view.findViewById(R.id.date_time);
            holder.llAdd = (LinearLayout) view.findViewById(R.id.sub_llAdd);
            holder.imgAdd = (WebView) view.findViewById(R.id.imgAdd);
            holder.imgAdd.setVerticalScrollBarEnabled(false);

            holder.short_text.setTypeface(typefont);
            holder.des.setTypeface(typefont);
            holder.date_time.setTypeface(typefont);
            holder.news_header_title.setTypeface(typefont);

        try{
             holder.image.setTag(NewsScreenActivity.arrayList_image.get(i));

                IL.DisplayImage(
                        ((NewsScreenActivity.ImagesData) ((NewsScreenActivity.StoryData) ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray
                                .get(position)).storyArr.get(i)).imageArr.get(0)).smallurl, holder.image);


                notifyDataSetChanged();

            } catch (Exception e) {
                // TODO: handle exception
            }

        try {


        holder.short_text.setText(((NewsScreenActivity.StoryData) ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray.get(position)).storyArr.get(i)).title);
        holder.des.setText(((NewsScreenActivity.StoryData) ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray.get(position)).storyArr.get(i)).description);


            String st = ((NewsScreenActivity.StoryData) ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray
                    .get(position)).storyArr.get(i)).date;
            parsed = new Date(Long.parseLong(st.substring(6, st.length() - 2)));

            SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy hh:mmaa");

            String concat = sdf.format(parsed);
            String data = concat;
            String half1 = data.substring(0, 11);


            SimpleDateFormat display_date = new SimpleDateFormat("dd.MM.yyyy");

            String dis_date = display_date.format(parsed);

            String half2 = data.substring(11, 19);


            SimpleDateFormat currentdate = new SimpleDateFormat("MMM dd,yyyy");
            Date currunt = new Date();
            String day = currentdate.format(currunt);

            if (half1.equalsIgnoreCase(day) == true) {
                holder.date_time.setText(half2);


            } else {
                half1 = dis_date;
                holder.date_time.setText(half1);

            }     

            holder.news_header_title.setText(((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray
                            .get(position)).catDisplay);


            if (!((NewsScreenActivity.StoryData) ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray
                    .get(position)).storyArr.get(i)).advertising
                    .equalsIgnoreCase("null")) {

                 holder.short_text.setVisibility(view.GONE);
                 holder.date_time.setVisibility(view.GONE);
                 holder.des.setVisibility(view.GONE);

                imgUrl = ((NewsScreenActivity.StoryData) ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray
                        .get(position)).storyArr.get(i)).adData.imageurl;

                // TODO Auto-generated method stub
                addurl = ((NewsScreenActivity.StoryData) ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray
                        .get(position)).storyArr.get(i)).adData.targeturl;


                //-----------------GIF Image view ------------

                holder.imgAdd.setOnTouchListener(NewsScreenAdapter.this);

                    client = new WebViewClient(){ 
                        @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { 
                            handler.sendEmptyMessage(CLICK_ON_URL);

                            return false;
                        } 
                    }; 

                    holder.imgAdd.setWebViewClient(client);
                    holder.imgAdd.setVerticalScrollBarEnabled(false);


                //    view.setVerticalScrollBarEnabled(false);



                holder.imgAdd.getSettings().setJavaScriptEnabled(true);

                holder.imgAdd.setWebChromeClient(new WebChromeClient() {
                        public void onProgressChanged(WebView view, int progress)
                        {

                            activity.setProgress(progress * 100);

                            if(progress == 100){}

                        }
                    });

                holder.imgAdd.setWebViewClient(new WebViewClient() {
                        @Override
                        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
                        {
                            // Handle the error
                        }

                        @Override
                        public boolean shouldOverrideUrlLoading(WebView view, String url)
                        {
                            view.loadUrl(url);
                            return true;
                        }
                    });

                holder.imgAdd.loadUrl(imgUrl);

            //  holder.imgAdd.setPadding(30, 20, 0, 20);


                holder.llAdd.setVisibility(View.VISIBLE);
              }

            holder.ll_data.addView(view);      


            view.setTag(position+"OK"+i);

            view.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    String tag = (String) v.getTag();
                    String[] arr = tag.split("OK");
                    int p = Integer.parseInt(arr[0]);
                    int i = Integer.parseInt(arr[1]);


                    str = ((NewsScreenActivity.StoryData) ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray .get(p)).storyArr.get(i)).storyid;


                    Intent intent = new Intent(context,ShowFullDescriprion.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                    intent.putExtra("id", str);
                    intent.putExtra("cat", p);
                    intent.putExtra("pos",i);
                    activity.startActivity(intent);
                }
            });
 } catch (Exception e) {
        // TODO: handle exception
                }
        }
        return vi;

    }



    public static String getDate(long milliSeconds, String dateFormat) {
        // Create a DateFormatter object for displaying date in specified
        // format.
        DateFormat formatter = new SimpleDateFormat(dateFormat);

        // Create a calendar object that will convert the date and time value in
        // milliseconds to date.
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(milliSeconds);
        return formatter.format(calendar.getTime());         
    }    
    public static class viewholder {

        TextView news_header_title, short_text, des, date_time;
        LinearLayout ll_data, llAdd;
        public ImageView image;
        WebView imgAdd;

    }
    private static final int CLICK_ON_WEBVIEW = 1;
    private static final int CLICK_ON_URL = 2;

    private Handler handler = new Handler(NewsScreenAdapter.this);


    @Override
    public boolean onTouch(View v, MotionEvent event) {
        // TODO Auto-generated method stub
          if (v.getId() == R.id.imgAdd && event.getAction() == MotionEvent.ACTION_DOWN){
                handler.sendEmptyMessageDelayed(CLICK_ON_WEBVIEW, 500);
            }
            return false;
    }
    public boolean handleMessage(Message msg) {
        if (msg.what == CLICK_ON_URL){
            handler.removeMessages(CLICK_ON_WEBVIEW);


            return true;
        }
        if (msg.what == CLICK_ON_WEBVIEW){

            activity.startActivity(new Intent(activity, AdvertismentActivity.class).putExtra("id", addurl));

            return true;
        }
        return false;
    }

    /* public void clearAllResources() {

            // Set related variables null

            System.gc();
            Runtime.getRuntime().gc();
           }*/
} 
4

2 回答 2

2

ListView 滚动的核心是 getView() 方法。
优化 getView() 方法将导致更快/更流畅的滚动。本视频中介绍了一些技术。你有一个视频,如果你没有时间看它,你有一个pdf 供下载

简而言之,它教您如何避免在不需要时在每次调用 getView() 时创建对象。
您的 getView()始终创建一个 TextView、一个 LinearLayout 和一个字体。只有当 convertview 为空时,您才应该创建所有这些,如果不是,则视图已经存在并且可以重用。
在链接的 pdf 中查找推荐的代码。

于 2013-02-25T06:28:34.443 回答
1

建议一:

getView方法中删除此行notifyDataSetChanged();

在它的 getView 方法中更新适配器的编码真的很差。

建议二:

不要在每次访问 get View 时重新创建所有内容。

如果视图已经创建,那么就使用它。

检查此代码:更新适配器代码

于 2013-02-25T12:49:46.140 回答