【问题标题】:ListView and items with countdown timerListView 和带有倒数计时器的项目
【发布时间】:2013-11-28 11:52:23
【问题描述】:

我的 Listview 有问题,我想为所有 ListView 的项目设置倒数计时器,并且我已经在谷歌上搜索了解决方案,但它无法正常工作。问题是 ListView 重用(回收)视图,我总是得到错误的项目时间。我为我的视图使用了一个标签,但它仍然不起作用,我不明白我在哪里犯了错误,请帮助我。谢谢。

所以这里有一张显示我的问题的图片: pic1 我刚开始一个活动的地方;

pic2 我刚刚向下和向上滚动的地方

这里是我的代码(全班):

更新

    public class PromoListActivity extends SherlockActivity {
private ListView mPromoList;
private PromoListAdapter mAdapter;
private ViewFlipper mFlipper;
private Button mBtnRepeat;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_news_list);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    setTitle("Сохранённые акции");
    mFlipper = (ViewFlipper) findViewById(R.id.flipper);
    mPromoList = (ListView) findViewById(R.id.newsList);
    mBtnRepeat = (Button) findViewById(R.id.btnRepeat);
    
    //-->
    final Handler timerHandler = new Handler();
    Runnable timerRunnable = new Runnable() {
        @Override
        public void run() {
            mAdapter.notifyDataSetChanged();
            timerHandler.postDelayed(this, 1000); // run every minute
        }
    };
    //<--
    
    
    mBtnRepeat.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            mFlipper.setDisplayedChild(0);
            getDummyData();
        }
    });
    mPromoList.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            startActivity(new Intent(PromoListActivity.this, PromoActivityDetails.class));

        }
    });
    getDummyData();
}

private class PromoListAdapter extends BaseAdapter {
    private ArrayList<PromoAction> mItems = new ArrayList<PromoAction>();
    private LayoutInflater layoutInflater;

    private PromoListAdapter(Context context, ArrayList<PromoAction> mItems) {
        layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.mItems = mItems;
    }

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

    public PromoAction getItem(int position) {
        return mItems.get(position);
    }

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

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewItem viewItem;
        PromoAction promoAction = getItem(position);
        if (convertView == null) {
            viewItem = new ViewItem();
            convertView = layoutInflater.inflate(R.layout.listviewitem_action, null);
            viewItem.name = (TextView) convertView.findViewById(R.id.promoAction_name);
            viewItem.desc = (TextView) convertView.findViewById(R.id.promoAction_desc);
            viewItem.timer = (TextView) convertView.findViewById(R.id.promoAction_timer);
            viewItem.timer.setTag(position);
            convertView.setTag(viewItem);
        } else {
            viewItem = (ViewItem) convertView.getTag();
        }
        setTime(promoAction,viewItem.timer,viewItem.timer.getTag().toString());
        viewItem.name.setText(promoAction.name);
        viewItem.desc.setText(promoAction.descr);
        return convertView;
    }

    private void setTime(final PromoAction promoAction, final TextView tv, final String tag) {
        if (tv.getTag().toString().equals(tag)) {
            long outputTime = Math.abs(promoAction.timer_end
                    - System.currentTimeMillis());
            Date date = new java.util.Date(outputTime);
            String result = new SimpleDateFormat("hh:mm:ss").format(date);
            tv.setText(result);
        }
    }

    public class ViewItem {
        TextView name;
        TextView desc;
        TextView timer;
    }
}

private void getDummyData() {
    ArrayList<PromoAction> list = new ArrayList<PromoAction>();
    for (int i = 1; i < 10; i++) {
        PromoAction action = new PromoAction();
        action.name = "Lorem ipsum dolor sit amet";
        action.descr = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ";
        switch (i) {
        case 1: {
            action.timer_start = 1385971000;
            action.timer_end = 1386104000;
        }
        case 2: {
            action.timer_start = 1385889000;
            action.timer_end = 1385812550;
            break;
        }
        case 3: {
            action.timer_start = 1385884200;
            action.timer_end = 1385912100;
            break;
        }
        default: {
            action.timer_start = 1385856000;
            action.timer_end = 1385892000;
            break;
        }
        }
        list.add(action);

    }
    mAdapter = new PromoListAdapter(PromoListActivity.this, list);
    mPromoList.setAdapter(mAdapter);
    mFlipper.setDisplayedChild(1);
}

}

【问题讨论】:

    标签: android listview countdowntimer multiplication


    【解决方案1】:

    在我的情况下,我以不同的方式解决了这个问题。每次调用getView() 时,我只需将当前时间和所需时间之间的时间差设置为TextView,而不是在getView() 中设置计时器处理程序。所以把你的这段代码移回getView()

    long outputTime = Math.abs(promoAction.timer_end
                        - System.currentTimeMillis());
    Date date = new java.util.Date(outputTime);
    String result = new SimpleDateFormat("hh:mm:ss").format(date);
    tv.setText(result);
    

    然后在 Activity 中创建一个处理程序,在列表视图的适配器上每隔一分钟调用一次notifyDatasetChanged()

    Handler timerHandler = new Handler();
    Runnable timerRunnable = new Runnable() {
        @Override
        public void run() {
            myAdapter.notifyDataSetChanged();
            timerHandler.postDelayed(this, 60000); //run every minute
        }
    };
    

    我在onPause() 上停止这个处理程序:

    @Override
    protected void onPause() {
        timerHandler.removeCallbacks(timerRunnable);
        super.onPause();
    }
    

    然后我在onResume() 重新开始:

    @Override
    protected void onResume() {
        timerHandler.postDelayed(timerRunnable, 500);
        super.onResume();
    }
    

    就是这样。 :)

    希望对你有帮助。

    【讨论】:

    • 我自己没有计时器,正如你看到我的代码,我使用处理程序来调用 notifyDataSetChanged() 就像你一样,我不明白为什么 listview 为它的孩子设置了错误的计时器,无论如何谢谢你的回答
    • @whizzzkey 您在getView() 中有计时器处理程序。不要那样做。尝试按照我的建议进行操作,看看是否有效。
    • hmm...您的解决方案根本不起作用,项目只有在它们离开屏幕时才会更新它们的时间,它仍然会查看缓存并显示错误的时间。我按照你写的做了。
    • 此外,您还需要在其外部启动处理程序。在您的onCreate() 中,只需在声明处理程序和可运行对象后添加timerHandler.postDelayed(timerRunnable, 500);
    • 如果你没有太多的项目,也许动态膨胀布局会更好。但是我上面给你的解决方案是有效的。我让它在我的一个应用程序上工作。希望您能找到适合您情况的解决方案。
    【解决方案2】:

    您可以使用回收站视图。从这里下载源代码()

    activity_main.xml

    <RelativeLayout android:layout_width="match_parent"
     android:layout_height="match_parent"
     xmlns:android="http://schemas.android.com/apk/res/android">
    
     <android.support.v7.widget.RecyclerView
     android:id="@+id/recycler_view"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:scrollbars="vertical" />
    
     </RelativeLayout>
    

    MainActivity.java

    package com.androidsolutionworld.multipletimer;
    
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.support.v7.widget.LinearLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.widget.LinearLayout;
    
    import java.util.ArrayList;
    
    public class MainActivity extends AppCompatActivity {
        private RecyclerView recyclerView;
        private ArrayList al_data = new ArrayList<>();
        private Adapter obj_adapter;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            recyclerView = (RecyclerView)findViewById(R.id.recycler_view);
            al_data.add("1234");
            al_data.add("1257");
            al_data.add("100");
            al_data.add("1547");
            al_data.add("200");
            al_data.add("500");
            al_data.add("2000");
            al_data.add("1000");
    
            obj_adapter = new Adapter(al_data);
            LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.VERTICAL,false);
            recyclerView.setLayoutManager(layoutManager);
            recyclerView.setAdapter(obj_adapter);
        }
    }
    

    adapter_layout.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="15dp"
            android:padding="10dp"
            android:id="@+id/tv_timer"/>
    
    </LinearLayout> 
    

    自定义适配器:

    package com.androidsolutionworld.multipletimer;
    
    
    import android.os.CountDownTimer;
    import android.support.v7.widget.RecyclerView;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.TextView;
    
    import java.util.ArrayList;
    
    public class Adapter extends RecyclerView.Adapter{
    
        private ArrayList al_data;
    
        public class MyViewHolder extends RecyclerView.ViewHolder{
            public TextView tv_timer;
            CountDownTimer timer;
    
            public MyViewHolder (View view){
                super(view);
                tv_timer = (TextView)view.findViewById(R.id.tv_timer);
    
            }
    
    
        }
    
        public Adapter(ArrayList al_data) {
            this.al_data = al_data;
        }
    
        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_layout,parent,false);
    
    
            return new MyViewHolder(view);
        }
    
        @Override
        public void onBindViewHolder(final MyViewHolder holder, int position) {
    
            holder.tv_timer.setText(al_data.get(position));
    
            if (holder.timer != null) {
                holder.timer.cancel();
            }
             long timer = Long.parseLong(al_data.get(position));
    
            timer = timer*1000;
    
            holder.timer = new CountDownTimer(timer, 1000) {
                public void onTick(long millisUntilFinished) {
                  holder.tv_timer.setText("" + millisUntilFinished/1000 + " Sec");
                }
    
                public void onFinish() {
                    holder.tv_timer.setText("00:00:00");
                }
            }.start();
    
    
        }
    
        @Override
        public int getItemCount() {
            return al_data.size();
        }
    
    
    
    }
    

    谢谢!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-12
      • 2021-03-29
      • 1970-01-01
      • 2013-01-26
      • 2019-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多