public class ListAdapter extends BaseAdapter{ PRivate List<Person> mList; private Context mContext; private int count=0; public ListAdapter(List<Person> list) { mList = list; } @Override public int getCount() { return mList!=null?mList.size():0; } @Override public Object getItem(int position) { return mList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { count++; Log.d("getView被调用的次数===",count+""); mContext=parent.getContext(); ViewHolder holder=null; if(convertView==null){ holder=new ViewHolder(); convertView= LayoutInflater.from(mContext).inflate(R.layout.list_item,parent,false); holder.mTextView= (TextView) convertView.findViewById(R.id.tv); convertView.setTag(holder); }else{ holder= (ViewHolder) convertView.getTag(); } String s = mList.get(position).getName(); holder.mTextView.setText(s); return convertView; } private static class ViewHolder{ TextView mTextView; }}public class Person { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; }}public class MainActivity extends AppCompatActivity { private ListView mListView; private List<Person> mList=new ArrayList<>(); private ListAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); initData(); setListener(); } private void setListener() { mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { int firstVisiblePosition = mListView.getFirstVisiblePosition(); //屏幕内当前可以看见的第一条数据 if(position-firstVisiblePosition>=0){ //1.获取当前点击的条目的view View itemView = mListView.getChildAt(position - firstVisiblePosition); //2.查找出相应的控件 TextView textView= (TextView) itemView.findViewById(R.id.tv); //3.更新ui textView.setText("我是更新后的数据"+position); //4.更新数据源 mList.get(position).setName("我是更新后的数据"+position); } } }); } private void initData() { Person person=null; for (int i = 0; i < 30; i++) { person=new Person(); person.setName("条目"+i); mList.add(person); } mAdapter=new ListAdapter(mList); mListView.setAdapter(mAdapter); } private void initView() { mListView= (ListView) findViewById(R.id.lv); }}
新闻热点
疑难解答