天天看點

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();
    }});
           

繼續閱讀