我正在创建一个需要每 x 秒更新一次列表的程序,所以我创建了一个 ListActivity 和一个线程。ListActivity 调用线程,并发送信息,但列表不会更新,直到所有线程完成。
示例:如果我在线程中放置了 5 次 for,则在 5 次结束之前您无法看到列表。
代码在这里:
列表活动:
public class ValuesActivity extends ListActivity {
ArrayList<Values> valueList;
ListView list;
ValuesAdapter adapter;
Request request;
String name;
NewValuesListener newValues;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.values);
list=(ListView)findViewById(android.R.id.list);
Bundle bundle=this.getIntent().getExtras();
name =bundle.getString("name");
newValues=new NewValuesListener(){
@Override
public void onNewValues(ArrayList<Values> val) {
valueList = val;
adapter=new ValuesAdapter(ValuesActivity.this,valueList);
adapter.notifyDataSetChanged();
list.setAdapter(adapter);
}
};
}
public void onResume(){
super.onResume();
valueList=new ArrayList<Values>();
request=new Request("XXXXXXXX",name,newValues);
adapter=new ValuesAdapter(this,valueList);
list.setAdapter(adapter);
request.run();
}
}
线:
public class Request extends Thread {
private String values;
private String server;
private NewValuesListener vActivity;
public Request(String values,String server,NewValuesListener activity){
this.values=values;
this.server=server;
this.vActivity=activity;
}
@Override
public void run() {
ConnectToServer con=new ConnectToServer(server);
int cd=5;
while (cd>0){
String response=con.read(values);
String[] channelValues=new String[2];
ArrayList<Values> arrValues=new ArrayList<Values>();
channelValues=LoadData.stringToArray(response);
for (int i=1;i<3;i++){
Values val=new Values("000"+i,channelValues[i]);
arrValues.add(val);
}
vActivity.onNewValues(arrValues);
try {
yield();
sleep(10000);
} catch (Exception e) {
e.printStackTrace();
}
cd--;
}
}
}
适配器:
public class ValuesAdapter extends BaseAdapter {
private ArrayList<Values> values;
private LayoutInflater lInflater;
public ValuesAdapter(Context context, ArrayList<Values> val) {
this.lInflater = LayoutInflater.from(context);
this.values = val;
}
@Override
public int getCount() {return values.size();}
@Override
public Object getItem(int arg0) {return values.get(arg0);}
@Override
public long getItemId(int arg0) {return arg0;}
@Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
ValuesView list = null;
if (arg1 == null){
arg1 = lInflater.inflate(R.layout.values_adapter, null);
list = new ValuesView();
list.channelName = (TextView) arg1.findViewById(R.id.lblValueName);
list.value = (EditText) arg1.findViewById(R.id.txtValue);
arg1.setTag(list);
} else
list = (ValuesView) arg1.getTag();
Values val = (Values) getItem(arg0);
list.channelName.setText(val.getName());
list.value.setText(val.getValue());
return arg1;
}
class ValuesView
{
TextView channelName;
EditText value;
}
}
知道为什么会这样吗?