跳至主要內容

列表与适配器

LincZero大约 1 分钟有道云

列表与适配器

列表与适配器

String[] companies = new String[] { "Google", "Apple", "Facebook",                                      // 适配器内容
         "Blackberry", "Samsung", "Twitter", "Intel", "HTC", "Asus" };
ListAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, companies);   // 调整适配器

ListView listView = (ListView) findViewById(R.id.mainListView1);                                      
listView.setAdapter(adapter);                                                                           // 控件设置适配器


listView.setOnItemClickListener(new OnItemClickListener() {                                             // 列表监听器
    @Override
    public void onItemClick(AdapterView<?> l, View v, int position, long id)                           // 方法
    {
        String s=(String) l.getItemAtPosition(position);
        Toast.makeText(MainActivity.this,s,Toast.LENGTH_SHORT).show();
    }
});

自定义列表

// 使用R.layout.entry布局中的R.id.entryTextView1控件
ListAdapter adapter = new ArrayAdapter<String>(this, R.layout.entry, R.id.entryTextView1, companies);

自定义适配器

...{...
        String[] companies = new String[] { "Google", "Apple", "Facebook", 
         "Blackberry", "Samsung", "Twitter", "Intel", "HTC", "Asus" };
    ListAdapter adapter = new MyAdapter(this, companies);                            // 使用自定义适配器
    
    ListView listView = (ListView) findViewById(R.id.mainListView1);
    listView.setAdapter(adapter);     
}

class MyAdapter extends ArrayAdapter<String>                                        // 继承了自带的适配器类,在此基础上进行拓展
{
    public MyAdapter(Context context, String[] values) 
    {
        super(context, R.layout.entry, values);                                     // 映射到父类中
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        LayoutInflater inflater = LayoutInflater.from(getContext());
        View view = inflater.inflate(R.layout.entry, parent, false);                // 使用的布局文件(里面有一个textView,一个imageView)
        
        String text = getItem(position);                                            // 获取item的字符串
        
        TextView textView = (TextView) view.findViewById(R.id.entryTextView1);      // 设置文本【注意这里是view.findViewById而非findViewById】
        textView.setText(text);
        
        ImageView imageView = (ImageView) view.findViewById(R.id.entryImageView1);  // 设置图像【注意这里是view.findViewById而非findViewById】
        imageView.setImageResource(android.R.drawable.ic_menu_info_details);
        if("Google".equals(text))
            imageView.setImageResource(android.R.drawable.ic_menu_gallery);
            
        return view;
    }
}