12、Dp Notes内容-列表(ListView使用)

        完成了一些空架子,开始填内容,从列表开始吧(主页没想好),列表很简单,一个ListView(从上往下能一直滑的那种,而且每块布局很类似)。ListView的使用和ViewPager很像,主要是Adapter。先在布局中引入ListView:
<ListView
    android:id="@+id/lv_list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/header_list" />

        ListFragment中定义ListView对象lv_list,从xml引入,不多说。ListView主要的一个方法setAdapter,可以通过Adapter控制ListView显示Item的个数,布局等等。新建包com.zdphpn.dpnotes.adapter,包中新建类ListAdapter,继承自BaseAdapter,有四个必须实现的方法,其中两个重要的,getCount(),ListView中显示Item个数,getView(),每个Item显示的内容,返回值View(可以通过将一个xml转为View返回)。另外再添加一个构造函数:
private Activity activity;
public ListAdapter(Activity activity){
    this.activity=activity;
}

        构造参数Activity activity(xml转View时用,所以构造函数传一个进来,也可以是其他的Context等)。先建一个ListView Item的布局文件item_list.xml,内容随意写了:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="@dimen/padding_s"
    android:paddingRight="@dimen/padding_s"
    android:paddingTop="@dimen/padding_ss"
    android:paddingBottom="@dimen/padding_ss" >
    
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:padding="@dimen/padding_n"
        android:background="@color/white_dark" >
    
        <TextView
            android:layout_width="wrap_content"
	    	android:layout_height="wrap_content"
	    	android:text="左" />
        <TextView
            android:layout_width="wrap_content"
	    	android:layout_height="wrap_content"
	    	android:layout_centerInParent="true"
	    	android:text="ListView Item" />

    </RelativeLayout>

</RelativeLayout>

        左右留点间距,ListView的滚动条位于Item外侧。ListAdapter的getView()引用:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    if(convertView==null){
        convertView=activity.getLayoutInflater().inflate(
R.layout.item_list, parent, false);
    }
    else{
        ;
    }
    return convertView;
}

        xml转为View返回,convertView先不说什么作用,getCount()函数返回值改为非0值。ListFragment中获取ListView对象并设置Adapter:
private View view;
private ListView lv_list;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    view=inflater.inflate(R.layout.fragment_list, container, false);
		
    lv_list=(ListView)view.findViewById(R.id.lv_list);
    lv_list.setAdapter(new ListAdapter(getActivity()));
		
    return view;
}

        注意是view.find(为什么呢?)。运行。

注:这是一个.gif动图,ctrl点击图片查看。Item的布局改过,不贴了。ListView使用是不是很简单?

始终如一——2016/11/01




猜你喜欢

转载自zdphpn.iteye.com/blog/2368279