我需要动态控制研究与AsyncTask的一个自定义的ListView的按钮的行为 [英] I need to dynamically controll the behaviour of a button of a custom listView with AsyncTask

查看:273
本文介绍了我需要动态控制研究与AsyncTask的一个自定义的ListView的按钮的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

林做一个电子商务应用程序,并在我的墙上我有很多产品(我称之为项目)。因此,所有这些项目通过自定义的的ListView 名为 ListViewAdapter 看到。在customListView的每一行有一个像的TextView 按钮查看元素C>,图片等。按钮我已经是一个后续按钮(这意味着如果用户是以下某一个项目这个按钮应该被视为灰色说法其次,如果用户没有遵循它,然后它应该是绿色的说法如下)。

所以,当我加载数据的的ListView 首次我需要做这个检查,看看是否一个项目是beeing跟随或没有(这个功能通过做后台服务器调用来完成,并根据我知道,如果它的beeing其次与否)的响应。再加上我需要实现一个功能,当我点击某一个项目它在后台服务器调用(得到一个结果= 0,如果操作succeded)的后续按钮,改变颜色和文字。

我做了一个管理查看秒的项目的ItemView控件类,在这里我的问题边棱:


  1. 如何管理的事实,我需要动态管理
    遵循按钮(很显然,我需要使用AsyncTask的),但我在哪里
    管理呢?在ItemView控件类或ListViewAdapter的每一行?


  2. 我需要管理这3个服务器调用一起:让所有的
    项目,看看哪一个之后还是不行,如果我选择一个项目
    遵循它。


我读了很多,我应该使用 adapter.notifyDataSetChanged(),但在哪里以及如何?

我敢肯定,我不是第一个人问这样的问题。我想,大多数电子商务的应用程序具有相同的行为。能否请你告诉我这是如何有效的进行。谢谢!

下面是我的code:

ListViewAdapter类

 公共类ListViewAdapter扩展ArrayAdapter<串GT; {    私人LayoutInflater吹气= NULL;    公共上下文的背景下;
    公众诠释layoutResourceId;
    公众的ArrayList<项目>项目;
    公共位图的图标;    公共ListViewAdapter(上下文的背景下,INT listviewItemRow,ArrayList的<项目>的项目,位图图标){
        // TODO自动生成构造函数存根
        超(背景下,listviewItemRow);
        this.items =物品;
        this.context =背景;
        this.icon =图标;
    }    @覆盖
    公共无效删除(String对象){
        // TODO自动生成方法存根
        super.remove(对象);
    }    @覆盖
    公众诠释的getCount(){
        返回items.size();
    }    公共项目的getItem(项目位置){
        返回的位置;
    }    @覆盖
    众长getItemId(INT位置){
        返回的位置;
    }    @覆盖
    公共查看getView(最终诠释的立场,观点convertView,父母的ViewGroup){        ItemView控件视图。
        如果(convertView == NULL){
            吹气=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            鉴于=(ItemView控件)inflater.inflate(R.layout.listview_item_row,NULL);
        }其他{
            鉴于=(ItemView控件)convertView;
        }        项目项目= items.get(位置);
        view.showItems(项目);
        view.setOnClickListener(新OnItemClickListener(位置));        返回视图。
    }    私有类OnItemClickListener实现OnClickListener {        私人诠释mPosition;        私人OnItemClickListener(INT位置){
            mPosition =位置;
        }        @覆盖
        公共无效的onClick(视图v){            Log.i(onListItemClickList,项目点:+ mPosition);
            Toast.makeText(背景下,信息+ Integer.toString(mPosition),Toast.LENGTH_SHORT).show();            意向意图=新意图(背景下,DettagliActivity.class);
            束束=新包();
            bundle.putInt(ID,mPosition);
            intent.putExtras(包);
            context.startActivity(意向);
        }
    }

ItemView控件类

 公共类ItemView控件扩展的LinearLayout实现AsyncResponse {    公众的TextView prezzo;
    公众的TextView scadenza;
    公共TextView的追随者;
    公共ImageView的ic_thumbnail;
    公众进度hProgressBar;
    公共切换按钮followButton;
    公共字符串nextFollowAction =;
    公共整数RESULT1 = 77;
    公众诠释状态code;
    公共项目的项目;    公共BackgroundTask mBackgroundTask = NULL;    公共ItemView控件(上下文的背景下,ATTRS的AttributeSet){
        超(背景下,ATTRS);
        //mBackgroundTask.delegate =这一点;
        // TODO自动生成构造函数存根
    }    @覆盖
    保护无效onFinishInflate(){
        super.onFinishInflate();        prezzo =(的TextView)findViewById(R.id.tv prezzo);
        scadenza =(的TextView)findViewById(R.id.tvScadenza);
        追随者=(的TextView)findViewById(R.id.tvFollowers);
        ic_thumbnail =(ImageView的)findViewById(R.id.ic_thumbnail);
        hProgressBar =(进度)findViewById(R.id.hProgressBar);
        followButton =(切换按钮)findViewById(R.id.btnFollow);
    }    公共无效showItems(最后一个项目项目){
        prezzo.setText(item.get prezzo());
        ic_thumbnail.setImageBitmap(item.getIcon());
        scadenza.setText(item.getScadenza());
        followers.setText(关注:+ item.getFollowers());
        hProgressBar.setProgress(item.getCoefficient());
        askForFollowing(kCheckFollowAction,项,3);
        mBackgroundTask =新BackgroundTask(本);
    mBackgroundTask.execute(item.getId(),(长)3);    followButton.setOnCheckedChangeListener(新CompoundButton.OnCheckedChangeListener(){
            公共无效onCheckedChanged(CompoundButton buttonView,布尔器isChecked){
                如果(器isChecked){
                    //启用的切换
                    Log.i(followButton,切换启用);
                    followButton.getTextOn();
                    mBackgroundTask =新BackgroundTask(ItemView.this);
                    mBackgroundTask.execute(item.getId(),(长),1);
                    // askForFollowing(RESULT1,nextFollowAction,项目);
                    // askForFollowing(状态code,nextFollowAction,项目);
                    increaseFollowers(项目);
                    followButton.setBackgroundResource(R.drawable.action_object_button_gray);
                }其他{
                    //肘被禁用
                    Log.i(followButton,切换已禁用);
                    mBackgroundTask =新BackgroundTask(ItemView.this);
                    mBackgroundTask.execute(item.getId(),(长)2);
                    // askForFollowing(RESULT1,nextFollowAction,项目);
                    followButton.getTextOff();
                    followButton.setBackgroundResource(R.drawable.action_object_button_green);
                    decreaseFollowers(项目);
                }
            }
        });
    }    公共无效setStatus code(INT状态code){
        this.status code =状态code;
    }
    公众诠释的getStatus code(项项目,诠释后续){
        //添加线程等待,直到你有状态code
        mBackgroundTask =新BackgroundTask(ItemView.this);
        mBackgroundTask.execute(item.getId(),(长)跟随);        返回状态code;
    }    公共无效askForFollowing(字符串nextFollowAction,项项,后续INT){
         Log.i(状态code是Integer.toString(状态code));
         Log.i(以下简称nextFollowAction是nextFollowAction);         INT状态code = $的getStatus C $ C(项,请);         //状态code:0 - >好
         如果(状态code == 0){
            Log.i(changeFollowStatus(nextFollowAction);,changeFollowStatus(nextFollowAction););
            nextFollowAction =kCheckFollowAction;
            changeFollowStatus(nextFollowAction,项目);
         }         //状态code 108 - > Oggetto GIA seguito
         否则,如果((状态code == 108)及及(nextFollowAction.contains(kCheckFollowAction))){
            Log.i(状态code == 108,状态code == 108);
            nextFollowAction =kUnfollowAction;
            followButton.setEnabled(真);
            followButton.setBackgroundResource(R.drawable.action_object_button_gray);
            followButton.setText(seguito);
         }         //状态code 122 - > Oggetto非安科拉seguito
         否则,如果((状态code == 122)及及(nextFollowAction.contains(kCheckFollowAction))){
            Log.i(状态code == 122,状态code == 122);
            nextFollowAction =kFollowAction;
            followButton.setEnabled(假);
            followButton.setBackgroundResource(R.drawable.action_object_button_green);
            followButton.setText(SEGUI);
         }
    }    公共无效changeFollowStatus(串动,项项){
        Log.i(changeFollowStatus行动,行动);        如果(action.contains(kFollowAction)){
            Log.i(changeFollowStatus,1);
            nextFollowAction =kUnfollowAction;
            followButton.setBackgroundResource(R.drawable.action_object_button_gray);
            followButton.setText(seguito);
            followButton.getTextOn();
            increaseFollowers(项目);
        }
        否则如果(action.contains(kUnfollowAction)){
            Log.i(changeFollowStatus,2);
            nextFollowAction =kFollowAction;
            followButton.setBackgroundResource(R.drawable.action_object_button_green);
            followButton.setText(SEGUI);
            followButton.getTextOff();
            decreaseFollowers(项目);
        }
    }    公共无效increaseFollowers(项目项目){
        INT updatedFollowers =的Integer.parseInt(item.getFollowers())+ 1;
        item.setFollowers(Integer.toString(updatedFollowers));
        followers.setText(关注:+ item.getFollowers());
    }    公共无效decreaseFollowers(项目项目){
        INT updatedFollowers =的Integer.parseInt(item.getFollowers()) - 1;
        item.setFollowers(Integer.toString(updatedFollowers));
        followers.setText(关注:+ item.getFollowers());
    }    @覆盖
    公共整数processFinish(整数结果){
        返回结果;
    }    / **
     *重新presents用来下载一个异步任务
     *从网络服务器的信息并显示结果
     * /
    公共类BackgroundTask扩展的AsyncTask<长,太虚,整数GT; {        //公共AsyncResponse代表;
        私人AsyncResponse侦听器;        公共BackgroundTask(AsyncResponse监听){
            this.listener =侦听器;
        }        @覆盖
        保护整数doInBackground(长... PARAMS){
            // TODO:对网络服务的尝试认证。            INT I = MVPFunctions.getInstance()。followItem(SessionManager.getUserDetails()。获得(登录),SessionManager.getUserDetails()。获得(密码),则params [0],则params [1] .intValue() );
            返回我;
        }        @覆盖
        在preExecute保护无效(){
            / *
             *这是在UI线程doInBackground之前执行()。它是
             *完美的地方,以显示进度对话框。
             * /
        }        @覆盖
        保护无效onPostExecute(整数结果){
            mBackgroundTask = NULL;
            RESULT1 = listener.processFinish(结果);            setStatus code(结果);            //delegate.processFinish(result);
            // ItemView控件
            //Log.i(\"onPostExecute状态code,Integer.toString(成功)+=+ Integer.toString(状态code));
        }        @覆盖
        保护无效onCancelled(){
            mBackgroundTask = NULL;
            // showProgress(假);
        }
    }
}

CompraFragment类

 公共类CompraFragment扩展ListFragment {    公众的ListView ListView的;
    公共ListViewAdapter适配器;
    公共布尔加载= FALSE;
    公共布尔get_all_items = FALSE;
    //公共PullToRefreshScrollView mPullRefreshScrollView;    / **
     *跟踪登录任务,以确保我们可以取消它,如果要求。
     * /
    私人DownloadTask mDownloadTask = NULL;
    私人布尔firstTime = TRUE;    //公共的ArrayList<&HashMap的LT;弦乐,对象>>项目=新的ArrayList<&HashMap的LT;弦乐,对象>>();
    公众的ArrayList<项目>项目=新的ArrayList<项目>();
    公共静态的ArrayList<龙> IDS =新的ArrayList<龙>();
    公共位图的图标;
    公众诠释currentItemId = 0;
    公共布尔noItems = FALSE;    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
    }    @覆盖
    公共查看onCreateView(LayoutInflater充气器,容器的ViewGroup,捆绑savedInstanceState){        //查看rootView = inflater.inflate(R.layout.fragment_compra,FALSE);
        查看rootView = inflater.inflate(R.layout.fragment_compra,集装箱,FALSE);        //现在你必须初始化列表视图
        ListView控件=(ListView控件)rootView.findViewById(android.R.id.list);        //mDownloadTask.execute((Void)NULL);
        mDownloadTask =新DownloadTask();
        mDownloadTask.execute(currentItemId);        返回rootView;
    }    / **
     *重新presents用来下载一个异步任务
     *从网络服务器的信息并显示结果
     * /
    公共类DownloadTask扩展的AsyncTask<整数,太虚,布尔> {        私人ProgressDialog progressDialog;        @覆盖
        保护布尔doInBackground(整数... PARAMS){
            // TODO:对网络服务的尝试认证。            如果(firstTime){
                IDS = MVPFunctions.getInstance()搜索()。
                firstTime = FALSE;
            }            如果(ids.isEmpty()){
                noItems = TRUE;
                返回false;
            }            INT current_id =参数[0];
            同时// 5要素
            INT计数器= 0;
            INT大小= ids.size();            而(计数器< = 5&安培;及(current_id<大小)){
                items.add(MVPFunctions.getInstance()的getItem(ids.get(current_id))。);
                current_id ++;
                反++;
                currentItemId = current_id;
            }            如果(current_id ==大​​小){
                get_all_items = TRUE;
            }            Log.i(current_id 2,Integer.toString(current_id));
            返回true;
        }        @覆盖
        在preExecute保护无效(){
            / *
             *这是在UI线程doInBackground之前执行()。它是
             *完美的地方,以显示进度对话框。
             * /
            progressDialog = ProgressDialog.show(getActivity(),,下载内容...);
        }        @覆盖
        保护无效onPostExecute(最终布尔成功){
            // mDownloadTask = NULL;            //让所有的产品后,关闭该对话框
            progressDialog.dismiss();
            加载= FALSE;
            // showProgress(假);            Log.i(onPostExecute,onPostExecute);            如果(noItems){
                Log.i(doInBackground2,项目空);
                Toast.makeText(getActivity(),非词索诺ELEMENTI哒caricare,Toast.LENGTH_LONG).show();
            }其他{
                        //从后台线程更新界面
                ListViewAdapter适配器=新ListViewAdapter(getActivity(),R.layout.listview_item_row,物品图标);
                        //更新列表视图
                    listView.setAdapter(适配器);                    listView.setOnScrollListener(新EndlessScrollListener());
            }        }        @覆盖
        保护无效onCancelled(){
            mDownloadTask = NULL;
            // showProgress(假);
        }    }    公共类EndlessScrollListener实现OnScrollListener {        私人INT visibleThreshold = 6;
        私人诠释previousTotal = 0;
        公共EndlessScrollListener(){
        }
        公共EndlessScrollListener(INT visibleThreshold){
            this.visibleThreshold = visibleThreshold;
        }        @覆盖
        公共无效onScroll(AbsListView观点,诠释firstVisibleItem,诠释visibleItemCount,诠释totalItemCount){
            如果(装载){
                如果(totalItemCount> previousTotal){
                    加载= FALSE;
                    previousTotal = totalItemCount;
                }
            }            如果(装载&放大器;!&放大器;!visibleItemCount = 0&放大器;及((firstVisibleItem + visibleItemCount)GT; =(totalItemCount))){
                如果((currentItemId&下; = ids.size())及&放大器;!get_all_items){
                    加载=真实的;
                    mDownloadTask =新DownloadTask();
                    mDownloadTask.execute(currentItemId);
                }
            }
            / *
            如果(visibleItemCount = 0&放大器;!及((firstVisibleItem + visibleItemCount)GT; =(totalItemCount))){
                如果(currentItemId&下; = ids.size()){
                    Log.i(3333如果,如果3333);
                    mDownloadTask =新DownloadTask();
                    mDownloadTask.execute(currentItemId);
                }
            }
            * /
        }        @覆盖
        公共无效onScrollStateChanged(AbsListView观点,诠释scrollState){
        }
    }
}


解决方案

尽量让所有的下面的数据:你填充的ListView了。

如果您可以编辑服务器端,写一个方法为它想获得跟随这些ID的状态。那么你的适配器getView方法可以检查布尔(类似:isFollowing())数据,并根据其更改按钮。
通过这种方式,你所要做的就是改变数据集和之后通知适配器。

这是确定列表视图与AsyncTask的修改单数的数据。

编辑:

如果是这样,你打电话给你的AsyncTask在你的适配器 getView()

  getView(){
    // convertView等。等等。做同样的东西来填充列表
    新CheckfollowTask(btnFollow,items.get(位置))执行();
}//类型参数可以在你需要改变这只是一个例子,一个伪。
类CheckfollowTask扩展的AsyncTask<太虚,太虚,太虚> {按钮btnFollow;
项项;
       CheckfollowTask(按钮btnFollow,项项){
       this.btnFollow = btnFollow;
       this.item =项目;
       }
      donInBackGround(){
      //从服务器获取数据
      }
      onPostExecute(){
      //设置btnFollow背景的东西,由于从服务器上你的回应。
      //不要忘记设置列表项跟随着状态。
      item.setFollow(响应);
      }}

Im making an ecommerce app, and on my wall i have many products (which i call items). So all these items are seen through a custom ListView called ListViewAdapter. each row of the customListView has various View elements like TextView, Button, Image, etc. The Button that i have is a follow button (meaning that if the user is following a certain item this button should be seen gray saying followed, if the user is not following it then it should be green saying follow).

So when i load the data in the ListView for the first time i need to do this check to see if an item is beeing followed or not (and this function is done by doing a server call in background and based on the response i know if its beeing followed or not). Plus i need to implement a function that when i click on the follow button of a certain item it does the server call in background (getting a result = 0 if the operation succeded), changes color and text.

I've made an ItemView class that manages the Views of an item, and my question arrises here:

  1. How do i manage the fact that i need to dynamically manage the follow Button (obviously i need to use AsyncTask), but where do i manage it? in the ItemView class or in ListViewAdapter for each row?

  2. I need to manage these 3 server calls all together: get all the items, see which one is followed or not, and if i select an item follow it.

I read a lot that i should use adapter.notifyDataSetChanged() but where and how ?

Im sure im not the first person to ask such a question. I imagine that most ecommerce apps have the same behaviour. Could you please show me how this is done efficiently. Thanks!

Here is my code:

ListViewAdapter class

public class ListViewAdapter extends ArrayAdapter<String> {

    private LayoutInflater inflater = null;

    public Context context; 
    public int layoutResourceId;
    public ArrayList<Item> items;
    public Bitmap icon;

    public ListViewAdapter(Context context, int listviewItemRow, ArrayList<Item> items, Bitmap icon) {
        // TODO Auto-generated constructor stub
        super(context, listviewItemRow);
        this.items = items;
        this.context = context;
        this.icon = icon;
    }

    @Override
    public void remove(String object) {
        // TODO Auto-generated method stub
        super.remove(object);
    }

    @Override
    public int getCount() {
        return items.size();
    }

    public Item getItem(Item position) {
        return position;
    }

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

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

        ItemView view;
        if (convertView == null) {
            inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = (ItemView) inflater.inflate(R.layout.listview_item_row, null);
        } else {
            view = (ItemView) convertView;
        }

        Item item = items.get(position);
        view.showItems(item);
        view.setOnClickListener(new OnItemClickListener(position));

        return view;
    }

    private class OnItemClickListener implements OnClickListener {

        private int mPosition;

        private OnItemClickListener(int position){
            mPosition = position;
        }

        @Override
        public void onClick(View v) {

            Log.i("onListItemClickList", "Item clicked: " + mPosition);
            Toast.makeText(context, "Message " + Integer.toString(mPosition), Toast.LENGTH_SHORT).show();

            Intent intent = new Intent(context, DettagliActivity.class);
            Bundle bundle = new Bundle();
            bundle.putInt("id", mPosition);
            intent.putExtras(bundle);
            context.startActivity(intent);
        }   
    }

ItemView class

public class ItemView extends LinearLayout implements AsyncResponse{

    public TextView prezzo;
    public TextView scadenza;
    public TextView followers;
    public ImageView ic_thumbnail;
    public ProgressBar hProgressBar;
    public ToggleButton followButton;
    public String nextFollowAction = "";
    public Integer result1 = 77;
    public int statusCode;
    public Item item;

    public BackgroundTask mBackgroundTask = null;

    public ItemView(Context context, AttributeSet attrs) {
        super(context, attrs);
        //mBackgroundTask.delegate = this;
        // TODO Auto-generated constructor stub
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        prezzo = (TextView)findViewById(R.id.tvPrezzo);
        scadenza = (TextView)findViewById(R.id.tvScadenza);
        followers = (TextView)findViewById(R.id.tvFollowers);
        ic_thumbnail = (ImageView)findViewById(R.id.ic_thumbnail);
        hProgressBar = (ProgressBar)findViewById(R.id.hProgressBar);
        followButton = (ToggleButton)findViewById(R.id.btnFollow);
    }

    public void showItems(final Item item) {
        prezzo.setText(item.getPrezzo());
        ic_thumbnail.setImageBitmap(item.getIcon());
        scadenza.setText(item.getScadenza());
        followers.setText("Followers:    " + item.getFollowers());
        hProgressBar.setProgress(item.getCoefficient());


        askForFollowing("kCheckFollowAction", item, 3);


        mBackgroundTask = new BackgroundTask(this);
    mBackgroundTask.execute(item.getId(), (long)3);

    followButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    // The toggle is enabled
                    Log.i("followButton", "toggle enabled");
                    followButton.getTextOn();
                    mBackgroundTask = new BackgroundTask(ItemView.this);
                    mBackgroundTask.execute(item.getId(), (long)1);
                    //askForFollowing(result1, nextFollowAction, item);
                    //askForFollowing(statusCode, nextFollowAction, item);
                    increaseFollowers(item);
                    followButton.setBackgroundResource(R.drawable.action_object_button_gray);
                } else {
                    // The toggle is disabled
                    Log.i("followButton", "toggle disabled");
                    mBackgroundTask = new BackgroundTask(ItemView.this);
                    mBackgroundTask.execute(item.getId(), (long)2);
                    //askForFollowing(result1, nextFollowAction, item);
                    followButton.getTextOff();
                    followButton.setBackgroundResource(R.drawable.action_object_button_green);
                    decreaseFollowers(item);
                }
            }
        });
    }

    public void setStatusCode(int statusCode){
        this.statusCode = statusCode;
    }


    public int getStatusCode(Item item, int follow){
        //add thread that waits untill you have the statusCode
        mBackgroundTask = new BackgroundTask(ItemView.this);
        mBackgroundTask.execute(item.getId(), (long) follow);

        return statusCode;
    }

    public void askForFollowing(String nextFollowAction, Item item, int follow){
         Log.i("The statusCode is", Integer.toString(statusCode));
         Log.i("The nextFollowAction is", nextFollowAction);

         int statusCode = getStatusCode(item, follow);

         //Status code: 0 --> OK
         if(statusCode == 0) {
            Log.i("changeFollowStatus(nextFollowAction);", "changeFollowStatus(nextFollowAction);");
            nextFollowAction = "kCheckFollowAction";
            changeFollowStatus(nextFollowAction, item);
         }

         // Status code 108 --> Oggetto già seguito
         else if ((statusCode == 108) && (nextFollowAction.contains("kCheckFollowAction"))) {
            Log.i("statusCode == 108", "statusCode == 108");
            nextFollowAction = "kUnfollowAction";
            followButton.setEnabled(true);
            followButton.setBackgroundResource(R.drawable.action_object_button_gray);
            followButton.setText("seguito");
         }

         // Status code 122 --> Oggetto non ancora seguito
         else if ((statusCode == 122) && (nextFollowAction.contains("kCheckFollowAction"))) {
            Log.i("statusCode == 122", "statusCode == 122");
            nextFollowAction = "kFollowAction";
            followButton.setEnabled(false);
            followButton.setBackgroundResource(R.drawable.action_object_button_green);
            followButton.setText("segui");
         }  
    }

    public void changeFollowStatus(String action, Item item){
        Log.i("changeFollowStatus action", action);

        if(action.contains("kFollowAction")) {
            Log.i("changeFollowStatus", "1");
            nextFollowAction = "kUnfollowAction";
            followButton.setBackgroundResource(R.drawable.action_object_button_gray);
            followButton.setText("seguito");
            followButton.getTextOn();
            increaseFollowers(item);        
        }
        else if(action.contains("kUnfollowAction")){
            Log.i("changeFollowStatus", "2");
            nextFollowAction = "kFollowAction";
            followButton.setBackgroundResource(R.drawable.action_object_button_green);
            followButton.setText("segui");
            followButton.getTextOff();
            decreaseFollowers(item);
        }
    }

    public void increaseFollowers(Item item){
        int updatedFollowers = Integer.parseInt(item.getFollowers()) + 1;
        item.setFollowers(Integer.toString(updatedFollowers));
        followers.setText("Followers:    " + item.getFollowers());
    }

    public void decreaseFollowers(Item item){
        int updatedFollowers = Integer.parseInt(item.getFollowers()) - 1;
        item.setFollowers(Integer.toString(updatedFollowers));
        followers.setText("Followers:    " + item.getFollowers());
    }

    @Override
    public Integer processFinish(Integer result) {
        return result;
    }

    /**
     * Represents an asynchronous  task used to download
     * information from the webserver and display the results
     */
    public class BackgroundTask extends AsyncTask<Long, Void, Integer> {

        //public AsyncResponse delegate;
        private AsyncResponse listener;

        public BackgroundTask(AsyncResponse listener){
            this.listener = listener;
        }

        @Override
        protected Integer doInBackground(Long... params) {
            // TODO: attempt authentication against a network service.

            int i = MVPFunctions.getInstance().followItem(SessionManager.getUserDetails().get("login"), SessionManager.getUserDetails().get("password"), params[0], params[1].intValue());
            return i;
        }

        @Override
        protected void onPreExecute(){
            /*
             * This is executed on UI thread before doInBackground(). It is
             * the perfect place to show the progress dialog.
             */
        }

        @Override
        protected void onPostExecute(Integer result) {
            mBackgroundTask = null;
            result1 = listener.processFinish(result);

            setStatusCode(result);

            //delegate.processFinish(result);
            //ItemView
            //Log.i("onPostExecute statusCode", Integer.toString(success) + " = " + Integer.toString(statusCode));
        }

        @Override
        protected void onCancelled() {
            mBackgroundTask = null;
            //showProgress(false);
        }
    }
}

CompraFragment class

public class CompraFragment extends ListFragment {

    public ListView listView;
    public ListViewAdapter adapter;
    public boolean loading = false;
    public boolean get_all_items = false;
    //public PullToRefreshScrollView mPullRefreshScrollView;

    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    private DownloadTask mDownloadTask = null;
    private Boolean firstTime = true;

    //public ArrayList<HashMap<String, Object>> items = new ArrayList<HashMap<String, Object>>();
    public ArrayList<Item> items = new ArrayList<Item>();
    public static ArrayList<Long> ids = new ArrayList<Long>();
    public Bitmap icon;
    public int currentItemId = 0;
    public Boolean noItems = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        //View rootView = inflater.inflate(R.layout.fragment_compra, false); 
        View rootView = inflater.inflate(R.layout.fragment_compra, container, false); 

        // now you must initialize your list view
        listView = (ListView) rootView.findViewById(android.R.id.list); 

        //mDownloadTask.execute((Void) null);   
        mDownloadTask = new DownloadTask();
        mDownloadTask.execute(currentItemId);

        return rootView;
    }

    /**
     * Represents an asynchronous  task used to download
     * information from the webserver and display the results
     */
    public class DownloadTask extends AsyncTask<Integer, Void, Boolean> {

        private ProgressDialog progressDialog;

        @Override
        protected Boolean doInBackground(Integer... params) {
            // TODO: attempt authentication against a network service.

            if (firstTime){
                ids = MVPFunctions.getInstance().search();
                firstTime = false;
            }

            if (ids.isEmpty()){
                noItems = true;
                return false;
            }

            int current_id = params[0];


            // 5 elements at a time
            int counter = 0;
            int size = ids.size();  

            while (counter <= 5 && (current_id < size)) {
                items.add(MVPFunctions.getInstance().getItem(ids.get(current_id)));
                current_id++;
                counter++;
                currentItemId = current_id;
            }

            if(current_id == size){
                get_all_items = true;
            }

            Log.i("current_id    2", Integer.toString(current_id));
            return true;
        }

        @Override
        protected void onPreExecute(){
            /*
             * This is executed on UI thread before doInBackground(). It is
             * the perfect place to show the progress dialog.
             */
            progressDialog = ProgressDialog.show(getActivity(), "", "Downloading Content...");
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            //mDownloadTask = null;

            // dismiss the dialog after getting all products
            progressDialog.dismiss();
            loading = false;
            //showProgress(false);

            Log.i("onPostExecute", "onPostExecute");

            if (noItems){
                Log.i("doInBackground2", "items null");
                Toast.makeText(getActivity(), "Non ci sono elementi da caricare", Toast.LENGTH_LONG).show();
            } else {
                        // updating UI from Background Thread
                ListViewAdapter adapter = new ListViewAdapter(getActivity(),R.layout.listview_item_row, items, icon);
                        // updating listview
                    listView.setAdapter(adapter);

                    listView.setOnScrollListener(new EndlessScrollListener());                          
            }

        }

        @Override
        protected void onCancelled() {
            mDownloadTask = null;
            //showProgress(false);
        }

    }

    public class EndlessScrollListener implements OnScrollListener {

        private int visibleThreshold = 6;
        private int previousTotal = 0;


        public EndlessScrollListener() {
        }
        public EndlessScrollListener(int visibleThreshold) {
            this.visibleThreshold = visibleThreshold;
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            if (loading) {
                if (totalItemCount > previousTotal) {
                    loading = false;
                    previousTotal = totalItemCount;
                }
            }

            if (!loading && visibleItemCount != 0 && ((firstVisibleItem + visibleItemCount) >= (totalItemCount))) {
                if ((currentItemId <= ids.size()) && !get_all_items){               
                    loading = true;
                    mDownloadTask = new DownloadTask();
                    mDownloadTask.execute(currentItemId);
                }
            }
            /*
            if (visibleItemCount != 0 && ((firstVisibleItem + visibleItemCount) >= (totalItemCount))) {
                if (currentItemId <= ids.size()){
                    Log.i("3333 if", "3333 if");
                    mDownloadTask = new DownloadTask();
                    mDownloadTask.execute(currentItemId);
                }
            }
            */
        }

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
        }
    }
}

解决方案

Try to get all "following data" before you populate the ListView.

If you can edit the server side, write a method for it like get "follow" status of these ids . then your adapters getView method can check the boolean (something like : isFollowing()) data and change the button according to it. By this way, all you have to do is changing the data set and notify the adapter after it.

it is ok to change singular data with asynctask in list view.

EDIT :

if it is so, you have to call your asynctask in your adapters getView() method

getView(){
    //convertView ect. blah. do the same stuff to populate your list
    new CheckfollowTask(btnFollow, items.get(position)).execute();


}

//Type parameters can change in your need this is just an example, a pseudo.
class CheckfollowTask extends AsyncTask<Void,Void,Void>{

Button btnFollow;
Item item;
       CheckfollowTask(Button btnFollow,Item item){
       this.btnFollow=btnFollow;
       this.item=item;
       }
      donInBackGround(){
      //get data from server
      }
      onPostExecute(){
      //set btnFollow's background to something due to your response from server.
      //don't forget to set your list items followin status.
      item.setFollow(response);
      }

}

这篇关于我需要动态控制研究与AsyncTask的一个自定义的ListView的按钮的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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