簡體   English   中英

Android創建具有多個倒數計時器的列表視圖不起作用

[英]Android creating listview with multiple countdown timer not working

我是android新手。 目前,當我嘗試在listfragment類的listview中的每個項目中創建倒數計時器時,我遇到問題。 計時器沒有倒計時,並且被卡在那里。 誰能幫我解決我的問題?

這是我的listview類。

public class OneFragment extends ListFragment {

View rootView;
TextView scheduleId;
ListAdapter listadapter;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    final DBController controller = new DBController(getActivity());
    final ArrayList<HashMap<String, String>> scheduleList = controller.getAllSchedules();
    if (scheduleList.size()!=0){
        ListView lv = getListView();
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                scheduleId = (TextView) view.findViewById(R.id.scheduleId);
                String getId = scheduleId.toString();
                int duration = Toast.LENGTH_SHORT;
                Toast toast = Toast.makeText(getActivity(), getId, duration);
                toast.show();
                controller.deleteSchedule(getId);
                onResume();
            }
        });
        ArrayList schedule = new ArrayList();
        schedule.clear();
        String query = "SELECT  * FROM schedules";
        Cursor c1 = controller.selectQuery(query);
        if (c1 != null & c1.getCount() != 0) { //if there is item in the cursor
            if (c1.moveToFirst()) {  //start to move to position
                do {
                    getSchedule schedule1 = new getSchedule();  //create object of the class getParticipant
                    schedule1.setscheduleId(c1.getString(c1
                            .getColumnIndex("scheduleId")));  //set the friend id in the object
                    schedule1.setscheduleName(c1.getString(c1
                            .getColumnIndex("scheduleName")));  //set the friend name in the object
                    schedule1.setscheduleDuration(c1.getString(c1.getColumnIndex("scheduleDuration")));
                    schedule.add(schedule1);  //add the object to arraylist
                } while (c1.moveToNext());  //if still have item in the cursor, loop again
            }
        }
        c1.close();
        listadapter = new ListAdapter(getActivity(), schedule);//create object of adapter class by
        //passing a context and arraylist
        listadapter.notifyDataSetChanged();
        setListAdapter(listadapter);  //set the adapter

    }
}

Handler handler = new Handler();
Runnable updateRunnable= new Runnable() {
    @Override
    public void run() {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {  listadapter.notifyDataSetChanged();     }
        });
        handler.postDelayed(this, 1000);
    }
};

@Override
public void onResume() {   //when user resume from an intent
    super.onResume();
    handler.post(updateRunnable);
    if (getListView() != null) {   //if the list view is not null
        updateData();     //call the method updateData() to update the listView
    }
}

@Override
public void onStop() {
    super.onStop();
    handler.removeCallbacks(updateRunnable);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    rootView = inflater.inflate(R.layout.fragment_one, container, false);
    return rootView;
}

public void updateData(){
    final DBController controller = new DBController(getActivity());
    final ArrayList<HashMap<String, String>> scheduleList = controller.getAllSchedules();
    if (scheduleList.size()!=0){
        ListView lv = getListView();
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                scheduleId = (TextView) view.findViewById(R.id.scheduleId);
                String getId = scheduleId.toString();
                int duration = Toast.LENGTH_SHORT;
                Toast toast = Toast.makeText(getActivity(), getId, duration);
                toast.show();
                controller.deleteSchedule(getId);
                onResume();
            }
        });
        ArrayList schedule = new ArrayList();
        schedule.clear();
        String query = "SELECT  * FROM schedules";
        Cursor c1 = controller.selectQuery(query);
        if (c1 != null & c1.getCount() != 0) { //if there is item in the cursor
            if (c1.moveToFirst()) {  //start to move to position
                do {
                    getSchedule schedule1 = new getSchedule();  //create object of the class getParticipant
                    schedule1.setscheduleId(c1.getString(c1
                            .getColumnIndex("scheduleId")));  //set the friend id in the object
                    schedule1.setscheduleName(c1.getString(c1
                            .getColumnIndex("scheduleName")));  //set the friend name in the object
                    schedule1.setscheduleDuration(c1.getString(c1.getColumnIndex("scheduleDuration")));
                    schedule.add(schedule1);  //add the object to arraylist
                } while (c1.moveToNext());  //if still have item in the cursor, loop again
            }
        }
        c1.close();
        ListAdapter listadapter = new ListAdapter(getActivity(), schedule);//create object of adapter class by
        //passing a context and arraylist
        listadapter.notifyDataSetChanged();
        setListAdapter(listadapter);  //set the adapter
    }
}
}

這是我的適配器類。

public class ListAdapter extends BaseAdapter {
Context ctx;
private CountDownTimer countDownTimer;
private long countdown;
private TextView scheduleDuration;
LayoutInflater lInflater;
private Handler mHandler = new Handler();
ArrayList<getSchedule> objects;

ListAdapter(Context context, ArrayList<getSchedule> scheduleList) {
    ctx = context;  //set the context
    objects = scheduleList; //set the arraylist
    lInflater = (LayoutInflater) ctx  //set the layout
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

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

@Override
public Object getItem(int position) {
    return objects.get(position);
}

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    getSchedule schedule = objects.get(position);
    final DBController controller = new DBController(ctx);
    View view = convertView;
    if (view == null) {  //if view is null
        view = lInflater.inflate(R.layout.view_schedule_entry, parent, false);
    }
    final TextView scheduleId = (TextView)view.findViewById(R.id.scheduleId);
    scheduleId.setText(schedule.getscheduleId());
    TextView scheduleName = (TextView)view.findViewById(R.id.scheduleName);
    scheduleName.setText(schedule.getscheduleName());
    scheduleDuration = (TextView)view.findViewById(R.id.scheduleDuration);
    int convert = Integer.parseInt(schedule.getscheduleDuration());
    countdown = 60 * convert * 1000;
    startTimer();
    return view;
}

private void startTimer() {

    countDownTimer = new CountDownTimer(countdown, 500) {
        // 500 means, onTick function will be called at every 500
        // milliseconds

        @Override
        public void onTick(long leftTimeInMilliseconds) {
            long seconds = leftTimeInMilliseconds / 1000;

            scheduleDuration.setText(String.format("%02d:%02d:%02d", seconds / 3600,
                    (seconds % 3600) / 60, (seconds % 60)));
            // format the textview to show the easily readable format

        }

        @Override
        public void onFinish() {
            // this function will be called when the timecount is finished
            scheduleDuration.setText("Time up!");
        }

    }.start();
}
}

這是我的getSchedule類:

public class getSchedule {
String scheduleId;
String scheduleName;
String scheduleDuration;

public String getscheduleId(){
    return scheduleId;
}

public void setscheduleId(String id){
    this.scheduleId=id;
}

public String getscheduleName(){
    return scheduleName;
}

public void setscheduleName(String name){
    this.scheduleName=name;
}

public String getscheduleDuration(){
    return scheduleDuration;
}

public void setscheduleDuration(String duration){
    this.scheduleDuration = duration;
}
}

我正在嘗試檢索數據庫中每個項目的持續時間(以分鍾為單位),並為列表視圖中的每個項目創建一個倒數計時器。 但是計時器只是停留在那兒...請幫助我。 謝謝。

使用更新的適配器

public class ListAdapter extends BaseAdapter {
    Context ctx;
    private CountDownTimer countDownTimer;
    private long countdown;
    private TextView scheduleDuration;
    LayoutInflater lInflater;
    private Handler mHandler = new Handler();
    ArrayList<getSchedule> objects;
    private String Duration = "";
    boolean flag = true;
    ListAdapter(Context context, ArrayList<getSchedule> scheduleList) {
        ctx = context;  //set the context
        objects = scheduleList; //set the arraylist
        lInflater = (LayoutInflater) ctx  //set the layout
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

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

    @Override
    public Object getItem(int position) {
        return objects.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        getSchedule schedule = objects.get(position);
        final DBController controller = new DBController(ctx);
        View view = convertView;
        if (view == null) {  //if view is null
            view = lInflater.inflate(R.layout.view_schedule_entry, parent, false);
        }
        final TextView scheduleId = (TextView)view.findViewById(R.id.scheduleId);
        scheduleId.setText(schedule.getscheduleId());
        TextView scheduleName = (TextView)view.findViewById(R.id.scheduleName);
        scheduleName.setText(schedule.getscheduleName());
        scheduleDuration = (TextView)view.findViewById(R.id.scheduleDuration);
        scheduleDuration.setText(Duration);
        int convert = Integer.parseInt(schedule.getscheduleDuration());
        countdown = 60 * convert * 1000;
        if(flag){
            startTimer();
            flag = false;
        }
        return view;
    }

    private void startTimer() {

        countDownTimer = new CountDownTimer(countdown, 500) {
            // 500 means, onTick function will be called at every 500
            // milliseconds

            @Override
            public void onTick(long leftTimeInMilliseconds) {
                long seconds = leftTimeInMilliseconds / 1000;

                Duration =String.format("%02d:%02d:%02d", seconds / 3600,
                        (seconds % 3600) / 60, (seconds % 60));
                // format the textview to show the easily readable format
                notifyDataSetChanged();

            }

            @Override
            public void onFinish() {
                // this function will be called when the timecount is finished
                Duration = "Time up!";
                notifyDataSetChanged();
            }

        }.start();

    }
}

每次加載視圖時,您都在啟動計時器。 這意味着,如果您在列表視圖中上下滾動幾次,最終可能會在后台運行數百次。 很壞。 您也沒有使用ViewHolder。 您應該使用其中一種,它將大大提高性能。除此以外,正確的方法對我來說似乎是以下情況。 (我最近做了完全一樣的事情)

您的getSchedule對象應該具有一個函數,該函數可以計算出該倒計時還剩多少時間:

public function String getTimeLeft(){
   String timeLeft;
   .
   .
   return timeLeft; 
}

並在適配器的getView方法中執行以下操作:

  timeLeftTextView.setText(getSchedule.getTimeLeft());

和你的活動

// class variables
Handler handler = new Handler(); 
Runnable updateRunnable= new Runnable() {
    @Override
    public void run() {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {  adapter.notifyDataSetChanged();     }
        });
        handler.postDelayed(this, 1000);
    }
};

@Override
protected void onResume() { 
    super.onResume(); 
    handler.postRunnable(updateRunnable);
}

@Override
protected void onStop() { 
    super.onStop(); 
    handler.removeCallbacks(updateRunnable);
}

並且不要忘記調用handler.removeCallbacks(updateRunnable);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM