今天要写的是不调用adapter的notifyDatasetChanged方法来刷新数据:代码如下:
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final ListView mListView=(ListView)findViewById(R.id.mListView); final List<String> list = new ArrayList<>(); for (int i=0;i<5;i++){ list.add("a"); } final MyAdapter adapter = new MyAdapter(this,list); mListView.setAdapter(adapter); Button btn = (Button)findViewById(R.id.btn); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { View updateView =mListView.getChildAt(2); list.set(2,"c"); adapter.updateView(updateView,2); } }); } }
adapter代码如下:
package com.acfun.mlistviewproject; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.util.List; /** * Created by user on 2016/1/18. */ public class MyAdapter extends BaseAdapter { public List<String> list; public Context mContext; ViewHolder holder; public MyAdapter(Context mContext, List<String> list) { this.list = list; this.mContext = mContext; } public int getCount() { return this.list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { holder = new ViewHolder(); LayoutInflater inflater = LayoutInflater.from(mContext); convertView = inflater.inflate(R.layout.item_layout, null); holder.textView = (TextView) convertView.findViewById(R.id.tv); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } setDate(holder, position); return convertView; } static class ViewHolder { TextView textView; } public void setDate(ViewHolder holder, int position) { holder.textView.setText(list.get(position).toString()); } public void updateView(View view, int itemIndex) { if (view == null) { return; } //从view中取得holder ViewHolder holder = (ViewHolder) view.getTag(); holder.textView = (TextView) view.findViewById(R.id.tv); setDate(holder, itemIndex); } }