天天看点

Android ListView 列表控件ListView

ListView

1.用于ListView的数据源

class xinxi{
    public xinxi(String name, String value, int picl){ Name = name; Value = value}
    String Name;
    String Value;
}

ArrayList<xinxi> arr = new ArrayList<xinxi>();  
arr.add(new xinxi("lx","59"));        //增加一个例子
           

2.用于ListView的数据适配器

class MyAdapter extends BaseAdapter{                                     //数据适配器类
    public int getCount() { return arr.size();} //一共有多少条数据
    public Object getItem(int position) { return arr.get(position);} //换回指定position位置的对象
    public long getItemId(int position) { return position;} ////换回指定position位置的ID
    public View getView(int position, View convertView, ViewGroup parent) { //获取一个View 一个项目/条目

        ViewHolder holder = null; //使用ViewHolder_性能优化

        if(convertView==null){ //复用View_性能优化
            convertView = View.inflate(MainActivity.this, R.layout.item1, null);

            holder = new ViewHolder();

            holder.mytn = (TextView) convertView.findViewById(R.id.Ttxtname);
            holder.myti = (ImageView) convertView.findViewById(R.id.Tpicl);
            holder.mysc = (Button) convertView.findViewById(R.id.Tbtnsc);

            convertView.setTag(holder);

        }

        holder = (ViewHolder)convertView.getTag();

        pot = position; //  private int pot;                       
        holder.mytn.setText(arr.get(position).Name);
        holder.myti.setBackgroundResource(arr.get(position).Picl);
        holder.mysc.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                arr.remove(pot);
                MyAdapter.this.notifyDataSetChanged();
                /*
                Builder builder = new Builder(MainActivity.this);     // 提示框  %~~
                builder.setTitle("你是否确定删除这条数据?");
                builder.setNegativeButton("取消", null);
                builder.setPositiveButton("确定", new  DialogInterface.OnClickListener(){
                public void onClick(DialogInterface dialog, int which) {
                    arr.remove(MainActivity.this.pot);
                    MyAdapter.this.notifyDataSetChanged(); //内容发生更改时更新
                }});
                builder.show();*/
            }});
        return convertView;
    }
 }

class ViewHolder{
    private TextView mytn;
    private ImageView myti;
    private Button mysc;
}
           

3.把数据适配器用于ListView

//ArrayAdapter myAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, getData());  //simple_expandable_list_item_1::系统自带界面
mylv.setAdapter(myAdapter);          //列表控件 赋予 数据适配器 绑定数据
    mylv.setOnItemClickListener(new OnItemClickListener() {           //单击事件
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
            Toast.makeText(getApplicationContext(), "选择:"+arg2+"个", Toast.LENGTH_SHORT).show();
    }});
           

继续阅读