使用ViewHolder来刷新某项数据,而不用每次都全部刷新数据。
继承BaseAdapter,新建ViewHolder类。
public class TestListAdapter extends BaseAdapter { private Context mContext; private ListstrList; public TestListAdapter(Context context, List list) { super(); this.mContext = context; this.strList = list; } @Override public int getCount() { // TODO Auto-generated method stub return strList.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return position; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub ViewHolder holder = null; if (null == convertView) { convertView = LayoutInflater.from(mContext).inflate(R.layout.line, null); holder = new ViewHolder(); holder.iDText = (TextView) convertView.findViewById(R.id.textView_id); holder.strText = (TextView) convertView.findViewById(R.id.textView_str); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.iDText.setText(position + ""); String str = strList.get(position); holder.strText.setText(str); return convertView; } private static class ViewHolder { private TextView iDText; private TextView strText; } public void updataView(int posi, ListView listView) { int visibleFirstPosi = listView.getFirstVisiblePosition(); int visibleLastPosi = listView.getLastVisiblePosition(); if (posi >= visibleFirstPosi && posi <= visibleLastPosi) { View view = listView.getChildAt(posi - visibleFirstPosi); ViewHolder holder = (ViewHolder) view.getTag(); String txt = holder.strText.getText().toString(); txt = txt + "++;"; holder.strText.setText(txt); strList.set(posi, txt); } else { String txt = strList.get(posi); txt = txt + "++;"; strList.set(posi, txt); } }}
在Activity中,调用updateView()方法,刷新数据。
public class MainActivity extends Activity { private MainActivity mContext; private EditText idEdit; private TextView textView; private ListstrList = new ArrayList (); private ListView listView; private TestListAdapter ListAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mContext = this; for (int i = 0; i < 100; i++) { strList.add("test data"); } idEdit = (EditText) findViewById(R.id.edittext_id); textView = (TextView) findViewById(R.id.textview_modify); listView = (ListView) findViewById(R.id.listview); ListAdapter = new TestListAdapter(mContext, strList); listView.setAdapter(ListAdapter); //动态刷新 textView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub String idStr = idEdit.getText().toString(); int idInt = Integer.parseInt(idStr); ListAdapter.updataView(idInt, listView);//动态修改 } }); }}
给出布局文件: