在Android中使用线程自定义ListView项目

时间:2013-02-14 09:32:33

标签: android multithreading multiprocessing

我使用自定义列表视图适配器创建了一个自定义ListView。我想在列表中的每个列表项中设置当前时间。列表框中的项目必须每秒更新当前时间。

MainActivity.java

package com.example.examapp;

import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import com.example.exambp.*;

import android.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.LabeledIntent;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {
    ListView lv;
    Activity act=this;
    List<ListViewItem> items;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        items=new ArrayList<ListViewItem>();    
        lv=(ListView)findViewById(R.id.listView1);





    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);


    }
    public void showData(View v)
    {
        IntentIntegrator i=new IntentIntegrator(this);
        i.initiateScan();
    }


    String[] onedata;
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
         IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
         if (scanResult != null) {
          String x=scanResult.getContents();
          EditText et=(EditText)findViewById(R.id.editText1);
          et.setText(x);                 
          addToList(x); 

         }

    }


    ListViewItem li;
    CustomListViewAdapter adapter;
    public void addToList(String str)
    {

          onedata=str.split("/");    
          li=new ListViewItem();

          li.enrollId="EnrollmentID: "+onedata[0].toString();
          li.ExamId="ExamID: "+onedata[1].toString();
          li.UserId="UserId: "+onedata[2].toString();
          li.StartedTime=onedata[3].toString();
          li.Duration=onedata[4].toString();
          li.AvailableTime="jiukjh";
          items.add(li);

          adapter=new CustomListViewAdapter(this, items);
          lv.setAdapter(adapter);


    }



}

activity_main.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_marginLeft="60dp"
        android:ems="10"
        android:inputType="text" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:onClick="showData"
        android:text="@string/btn_val" />

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:orientation="vertical" >
    </LinearLayout>

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView9"
        android:layout_toRightOf="@+id/linearLayout2" >
    </ListView>

    <TextView
        android:id="@+id/textView9"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/button1"
        android:text="Started Exams"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

item_row.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/txtAvailability"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="TextView"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/txtEnrollmentId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/txtAvailability"
        android:text="TextView" />

    <TextView
        android:id="@+id/txtUserId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/txtEnrollmentId"
        android:layout_alignBottom="@+id/txtEnrollmentId"
        android:layout_marginLeft="78dp"
        android:layout_toRightOf="@+id/txtAvailability"
        android:text="TextView" />

    <TextView
        android:id="@+id/txtExamId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/txtEnrollmentId"
        android:text="TextView" />

    <TextView
        android:id="@+id/txtStartTime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/txtExamId"
        android:layout_alignBottom="@+id/txtExamId"
        android:layout_alignLeft="@+id/txtUserId"
        android:text="TextView" />

</RelativeLayout>

CustomListViewAdapter.java

package com.example.examapp;



import java.util.Date;
import java.util.List;

import com.example.exambp.*;

import android.app.Activity;  
import android.content.Context;
import android.view.LayoutInflater;  
import android.view.View;  
import android.view.ViewGroup;  
import android.widget.BaseAdapter;  
import android.widget.ImageView;  
import android.widget.ListView;
import android.widget.TextView;  

public class CustomListViewAdapter extends BaseAdapter
{  

    LayoutInflater inflater;
    List<ListViewItem> items;
    Activity act;
    public CustomListViewAdapter(Activity context, List<ListViewItem> items) {  
        super();

        this.items = items;
        this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.act=context;

    }

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

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

    @Override  
    public long getItemId(int position) {  
        // TODO Auto-generated method stub  
        return 0;  
    }
    View vi;   
    @Override  
    public View getView(final int position, View convertView, ViewGroup parent) {  
        // TODO Auto-generated method stub  
        ListViewItem item=items.get(position);

        vi=convertView;

        if(convertView==null)
            vi = inflater.inflate(R.layout.item_row, null);

        //ImageView imgThumbnail=(ImageView)vi.findViewById(R.id.imgThumbnail);
        TextView txtAvailableTime1=(TextView)vi.findViewById(R.id.txtAvailability);
        TextView txtEnrollmentId1=(TextView)vi.findViewById(R.id.txtEnrollmentId);
        TextView txtUserId1=(TextView)vi.findViewById(R.id.txtUserId);
        TextView txtExamId1=(TextView)vi.findViewById(R.id.txtExamId);
        TextView txtStartedTime1=(TextView)vi.findViewById(R.id.txtStartTime);

        //imgThumbnail.setImageResource(item.ThumbnailResource);
        txtAvailableTime1.setText(item.AvailableTime.toString());
        txtEnrollmentId1.setText(item.enrollId.toString());
        txtUserId1.setText(item.UserId.toString());
        txtExamId1.setText(item.ExamId.toString());
        txtStartedTime1.setText(item.StartedTime.toString());


        Thread myThread = null;
        Runnable runnable = new CountDownRunner();
        myThread= new Thread(runnable);   
        myThread.start();

        return vi;  
    }

    public void doWork() {
        act.runOnUiThread(new Runnable() {
            public void run() {
                try{

                        TextView txtCurrentTime=(TextView)vi.findViewById(R.id.txtAvailability);
                        Date dt = new Date();
                        int hours = dt.getHours();
                        int minutes = dt.getMinutes();
                        int seconds = dt.getSeconds();
                        String curTime = hours + ":" + minutes + ":" + seconds;
                        txtCurrentTime.setText(curTime);

                }catch (Exception e) {
                    //TextView txtCurrentTime=(TextView)vi.findViewById(R.id.txtAvailability);
                     //txtCurrentTime.setText(e.getMessage());
                }
            }
        });
    }

    class CountDownRunner implements Runnable{
        // @Override
        public void run() {
                while(true){
                    try {
                        doWork();
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                    }catch(Exception e){
                    }
                }
        }

    }
}

这只能一次运行。我想连续更改列表项中的当前时间。

1 个答案:

答案 0 :(得分:0)

每秒您都必须遍历List<ListViewItem>项目中的每个项目,然后更新每个项目的时间。之后致电listView.notifyDataSetChanged()