码迷,mamicode.com
首页 > 移动开发 > 详细

Android ListView

时间:2015-08-02 19:52:57      阅读:328      评论:0      收藏:0      [点我收藏+]

标签:

ListView遵循了MVC的设计理念。

model:ListView的数据部分

View:ListView呈现的界面

Controller:ListView的适配器

根据需求,我们可以采取不同的适配器来构建ListVIew。

ListView的适配器分为4种:ArrayAdapter、SimpleAdapter、SimpleCursorAdapter、自定义Adapter。

使用IDE:AndroidStudio

一、ArrayAdapter

public ArrayAdapter (Context context, int resource, int textViewResourceId, List<T> objects);//其中的一个构造方法

resource:布局文件的id

textViewResourceId:布局文件中TextView的id

objects:ListView数据

注意:ListView展现的数据是T类型数据的toString()方法的返回值。

1.核心java代码

setContentView(R.layout.activity_array_adapter);
listView = (ListView) findViewById(R.id.array_adapter_listview);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.item,R.id.listview_item,getArrayAdapterData());
listView.setAdapter(adapter);
...
...
public List<String> getArrayAdapterData(){ List<String> list = new ArrayList<>(); for(int i=0;i<20;i++){ list.add("Item "+i); } return list; }

2.activity_array_adapter.xml内容如下:

<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/array_adapter_listview"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

3.item.xml内容如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">
    <TextView
        android:id="@+id/listview_item"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="16sp"
        android:textColor="@android:color/holo_blue_light"
        android:layout_margin="5dp"/>
</LinearLayout>

特点:仅能展示一个TextView框!

4.效果:

技术分享

二、SimpleAdapter

 构造方法及说明:

技术分享

使用:

1.java代码

 private ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_simple_adapter);
        listView = (ListView) findViewById(R.id.simple_adapter_listview);
        SimpleAdapter adapter = new SimpleAdapter(getApplicationContext(),getSimpleAdapterData(),R.layout.simple_adapter_item,new String[]{"name","age"},new int[]{R.id.name,R.id.age});
        listView.setAdapter(adapter);
    }

    public List<Map<String,String>> getSimpleAdapterData(){
        List<Map<String,String>> data = new ArrayList<>();
        for(int i=0;i<20;i++){
            Map<String,String> item = new HashMap<>();
            item.put("name","I‘m "+i);
            item.put("age",i+10+"");
       data.add(item);
        }
        return data;
    }

 

2.activity_simple_adapter.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="vertical">
    <TextView android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:textColor="@android:color/holo_blue_dark"/>
    <TextView android:id="@+id/age"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="14sp"
        android:textColor="@android:color/holo_blue_light"/>
</LinearLayout>

3.simple_adapter_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="vertical">
    <TextView android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:textColor="@android:color/holo_blue_dark"/>
    <TextView android:id="@+id/age"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="14sp"
        android:textColor="@android:color/holo_blue_light"/>
</LinearLayout>

4.效果

技术分享

特点:可以将数据绑定到特定的layout中。缺点也很明显,ListView中的样式只能有一个,另外,与ListView中的item发生交互变得很不方便。

三、SimpleCursorAdapter

官方文档中有这样的描述:An easy adapter to map columns from a cursor to TextViews or ImageViews defined in an XML file. You can specify which columns you want, which views you want to display the columns, and the XML file that defines the appearance of these views。

简单的说就是方便把从游标得到的数据进行列表显示,并可以把指定的列映射到对应的xml布局文件中。

下面是展示联系人的例子:

1.构造方法

技术分享

2.增加读取联系人权限

<uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>

3.java代码

public class SimpleCursorAdapterActivity extends AppCompatActivity {

    private ListView listView;
    private SimpleCursorAdapter mAdapter;
    static final String[] PROJECTION = new String[] {ContactsContract.CommonDataKinds.Phone._ID,
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
            ContactsContract.CommonDataKinds.Phone.NUMBER};

    private LoaderManager.LoaderCallbacks<Cursor> loaderCallbacks = new LoaderManager.LoaderCallbacks<Cursor>() {
        @Override
        public Loader<Cursor> onCreateLoader(int id, Bundle args) {
            return new CursorLoader(SimpleCursorAdapterActivity.this, ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    PROJECTION, null, null,null);
        }

        @Override
        public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
            Toast.makeText(getApplicationContext(),""+data.getCount(),Toast.LENGTH_SHORT).show();
            mAdapter.swapCursor(data);
        }

        @Override
        public void onLoaderReset(Loader<Cursor> loader) {

        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_simple_cursor_adapter);
        listView = (ListView) findViewById(R.id.simple_cursor_adapter_listview);
        // Create an empty adapter we will use to display the loaded data.
        mAdapter = new SimpleCursorAdapter(this,
                R.layout.simple_cursor_adapter_item, null,
                new String[] { ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER },
                new int[] {R.id.contract_name, R.id.contract_phone },0);
        listView.setAdapter(mAdapter);
        getLoaderManager().initLoader(0, null, loaderCallbacks);

    }
}

4.activity_simple_cursor_adapter.xml

<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/simple_cursor_adapter_listview"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</ListView>

5.simple_cursor_adapter_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/contract_name"
        android:layout_width="match_parent"
        android:background="#AABBCC"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/contract_phone"
        android:layout_width="match_parent"
        android:background="#CCBBAA"
        android:layout_height="wrap_content" />
</LinearLayout>

6.效果

技术分享

注意事项:将cursor中数据映射到ListView时,cursor中必须要有_ID字段,如上述的 ContactsContract.CommonDataKinds.Phone._ID

四、自定义Adapter

 很多情况下,上述几种Adapter不能够满足需求,这时就需要自定义Adapter。

CustomedAdapter.java

class CustomedAdapter extends BaseAdapter {
        List<Map<String,String>> mData;
        LayoutInflater mInflater;
        Context mContext;
        public CustomedAdapter(Context context ,List<Map<String,String>> data,LayoutInflater layoutInflater){
            mData = data;
            mContext = context;
            mInflater = layoutInflater;
        }

        @Override
        public int getCount() {
            return mData.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                holder=new ViewHolder();
                convertView = mInflater.inflate(R.layout.customed_adapter_item, null);
                holder.title = (TextView)convertView.findViewById(R.id.title);
                holder.info = (TextView)convertView.findViewById(R.id.info);
                holder.viewBtn = (Button)convertView.findViewById(R.id.view_btn);
                convertView.setTag(holder);
            }else {
                holder = (ViewHolder)convertView.getTag();
            }
            holder.title.setText((String)mData.get(position).get("title"));
            holder.info.setText((String)mData.get(position).get("info"));

            holder.viewBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(mContext, "clicked button" + position, Toast.LENGTH_SHORT).show();
                }
            });
            return convertView;
        }


        public final class ViewHolder{
            public TextView title;
            public TextView info;
            public Button viewBtn;
        }
    }

2.java代码

public class CustomedAdapterActivity extends AppCompatActivity {

    private ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customed_adapter);
        listView = (ListView) findViewById(R.id.customed_listview);
        CustomedAdapter adapter = new CustomedAdapter(this,getData(),getLayoutInflater());
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(CustomedAdapterActivity.this,"clicked item"+position,Toast.LENGTH_SHORT).show();
            }
        });
    }


    private List<Map<String, String>> getData() {
        List<Map<String, String>> list = new ArrayList<>();

        HashMap<String, String> map = new HashMap<>();
        map.put("title", "G1");
        map.put("info", "google 1");
        list.add(map);

        map = new HashMap<>();
        map.put("title", "G2");
        map.put("info", "google 2");
        list.add(map);

        map = new HashMap<>();
        map.put("title", "G3");
        map.put("info", "google 3");
        list.add(map);

        return list;
    }

}

3.布局文件activity_customed_adapter.xml

<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/customed_listview"/>

4.customed_adapter_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <LinearLayout android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <TextView android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#FFFFFFFF"
            android:textSize="22px" />
        <TextView android:id="@+id/info"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#FFFFFFFF"
            android:textSize="13px" />

    </LinearLayout>


    <Button android:id="@+id/view_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="我是按钮"
        android:focusable="false"
        android:layout_gravity="bottom|right" />
</LinearLayout>

注意 <Button>标签中的android:focusable="false",如果该属性值设为true(默认true),则ListView的焦点集中在Button上,点击其他区域没反应。

5.效果

点击Button,Toast显示:

技术分享

点击按钮外的区域,显示:

技术分享

特点:灵活,可以细化到每个item的交互事件。

 

Android ListView

标签:

原文地址:http://www.cnblogs.com/ruyingxiangsui/p/4695451.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!