ListView显示Sqlite的数据美化版与性能优化

在上一篇文章中,我们已经实现在listview显示数据库内容的。但是我们listview中,排版不是很好看,所以这篇文章呢,我们来对listveiw进行美化。哈哈,说白了,就是对listview添加一个布局文件,然后把布局文件转化为view对象显示出来。

这里代码我们不贴全部,就贴上新增加的布局文件和有做修改的方法。

先看图片吧。

然后看listview的布局文件,其实从这个例子,大家可以知道,listview的项目可以显示很复杂的东西,只要是view对象都是可以显示的额,只要你的布局文件写好了。都可以。

list_layout.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="match_parent" >

    <TextView
        android:textSize="20sp"
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="名字" />

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

        <TextView
            android:id="@+id/age"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="年龄" />

        <TextView
            android:id="@+id/phone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="手机" />
    </LinearLayout>

</RelativeLayout>
复制代码

 MainActivity.java  这里只贴出修改的地方,其实也就是修改了 getView的几条语句而已。这里写出 getView方法的内容

复制代码
public View getView(int position, View convertView, ViewGroup parent) {
            Girl girl = girList.get(position); 
        /*    TextView tv = new TextView(MainActivity.this);
            tv.setTextSize(18);
            //获取集合中的元素
            tv.setText(girl.toString());*/
            View v ;
            /*
             * 做判断是为了listview的性能优化,converView表示一个缓冲区域。
             * 在看过的条目,离开屏幕后,其实会被缓冲起来,所以我们没必要
             * 每一次都去 填充,可以先判断是否有缓冲
             * 
             * */
            if(convertView ==null){
            //把ListView的布局文件填充为View对象
               v = View.inflate(MainActivity.this, R.layout.list_layout, null);
            }else{
                v = convertView ;
            }
            /*v.findViewById(R.id.name);前面加v是因为找的布局文件元素是listView对象的
             * 而v加载的布局文件就是listview的布局文件
            */
            TextView name = (TextView)v.findViewById(R.id.name);
            name.setText(girl.getName());
            TextView age = (TextView) v.findViewById(R.id.age);
            age.setText(girl.getAge()+"");
            TextView phone = (TextView)v.findViewById(R.id.phone);
            phone.setText(girl.getPhone());
            return v;
        }
        
复制代码

 

posted @   _Vincent  阅读(696)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示