android 个人学习笔记------------GridView&ListView

原创 2016年08月31日 14:05:58

MainActivity

package com.sjm.gridviewAndListview;

import com.sjm.expandableListview.ExpandableListviewActivity;
import com.sjm.gridview.R;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * gridView组件+listView组件
 * 
 * listview优化:
 * 
 * 1、使用固定的宽高,便面内容的变化导致重复渲染
 * 
 * 2、使用convertView减少内存的消耗
 * 
 * 3、使用viewHolder减少对象的查找
 * 
 * @author sjm
 *
 */
public class MainActivity extends Activity {

    private GridView gridView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        gridView = (GridView) findViewById(R.id.gridView);

        gridView.setAdapter(new MyAdapter(this));
        gridView.setOnItemClickListener(new OnItemClickListener() {

            /**
             * parent:girdView
             * 
             * view:item布局
             * 
             * position:位置----->坐标从0开始
             * 
             * id:编号
             */
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                TextView tv_item = (TextView) view.findViewById(R.id.tv_item);
                String itemValue = tv_item.getText().toString();

                if (itemValue.equals("红包")) {
                    Intent intent = new Intent(MainActivity.this, ListViewActivity1.class);
                    startActivity(intent);

                } else if (itemValue.equals("查询")) {
                    Intent intent = new Intent(MainActivity.this, ListViewActivity2.class);
                    startActivity(intent);
                } else if (itemValue.equals("基金")) {
                    Intent intent = new Intent(MainActivity.this, ListViewActivity3.class);
                    startActivity(intent);
                } else if (itemValue.equals("商城")) {
                    Intent intent = new Intent(MainActivity.this, ListViewNotifyDataSetChanged.class);
                    startActivity(intent);
                }else if (itemValue.equals("国债")) {
                    Intent intent = new Intent(MainActivity.this, ExpandableListviewActivity.class);
                    startActivity(intent);
                } else {
                    Toast.makeText(getApplicationContext(), "选择了第" + (id + 1) + "张图片-----" + "值为:" + itemValue,
                            Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    /**
     * 自定义适配器------>继承BaseAdapter
     * 
     * @author sjm
     *
     */
    static class MyAdapter extends BaseAdapter {

        private Context context;

        private MyAdapter(Context context) {
            this.context = context;
        }

        private int[] images = { R.drawable.sample_0, R.drawable.sample_1, R.drawable.sample_2, R.drawable.sample_3,
                R.drawable.sample_4, R.drawable.sample_5, R.drawable.sample_6, R.drawable.sample_7, R.drawable.sample_0,
                R.drawable.sample_1, R.drawable.sample_2, R.drawable.sample_3, R.drawable.sample_4, R.drawable.sample_5,
                R.drawable.sample_6, R.drawable.sample_7, R.drawable.sample_0, R.drawable.sample_1, R.drawable.sample_2,
                R.drawable.sample_3, R.drawable.sample_4, R.drawable.sample_5, R.drawable.sample_6, R.drawable.sample_7,
                // R.drawable.sample_thumb_0, R.drawable.sample_thumb_1,
                // R.drawable.sample_thumb_2,
                // R.drawable.sample_thumb_3, R.drawable.sample_thumb_4,
                // R.drawable.sample_thumb_5,
                // R.drawable.sample_thumb_6, R.drawable.sample_thumb_7
        };

        private String[] appNames = { "转账", "查询", "金融", "基金", "国债", "贷款", "信用卡", "商城", "充值", "提款", "红包", "贷款", "转账",
                "查询", "金融", "基金", "国债", "红包", "转账", "查询", "金融", "基金", "国债", "贷款" };

        @Override
        public int getCount() {
            // TODO 数据的长度
            return images.length;// or appNames.length
        }

        @Override
        public Object getItem(int position) {
            // TODO 获取每一个选项
            return appNames[position];
        }

        @Override
        public long getItemId(int position) {
            // TODO 每一个选项的id,直接使用position
            return position;
        }

        /**
         * convertView:减少对面的创建
         * 
         * ViewHolder:查询id,避免已经存在的时候重复查找
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder holder;
            // TODO 填充数据
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(R.layout.item_gridview, null);
                holder = new ViewHolder();

                holder.iv_item = (ImageView) convertView.findViewById(R.id.iv_item);
                holder.tv_item = (TextView) convertView.findViewById(R.id.tv_item);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            // ImageView iv_item = (ImageView)
            // convertView.findViewById(R.id.iv_item);
            // TextView tv_item = (TextView)
            // convertView.findViewById(R.id.tv_item);

            holder.iv_item.setImageResource(images[position]);
            holder.tv_item.setText(appNames[position]);

            return convertView;
        }

        /**
         * 用于第一次查找组件,避免下一次重复查找
         * 
         * @author sjm
         *
         */
        static class ViewHolder {
            ImageView iv_item;
            TextView tv_item;
        }
    }

}

```**ListViewActivity1**





<div class="se-preview-section-delimiter"></div>

这里写代码片
“`

package com.sjm.gridviewAndListview;

import com.sjm.gridview.R;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * listview 基本用法
 * 
 * @author sjm
 *
 */
public class ListViewActivity1 extends Activity {

    private ListView lv_listview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setContentView(R.layout.listview1_layout);
        lv_listview = (ListView) findViewById(R.id.lv_listview);
        lv_listview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView textValue = (TextView) view;
                Toast.makeText(ListViewActivity1.this, "当前点击结果为:" + textValue.getText().toString(),
                        Toast.LENGTH_LONG).show();

            }
        });
    }
}

```**ListViewActivity2**





<div class="se-preview-section-delimiter"></div>

这里写代码片
“`

package com.sjm.gridviewAndListview;

import com.sjm.gridview.R;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * ListActivity的基本用法,不需要自己写xml布局文件
 * 
 * @author sjm
 *
 */
public class ListViewActivity2 extends ListActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ArrayAdapter<?> adapter = ArrayAdapter.createFromResource(getApplicationContext(), R.array.name,
                android.R.layout.simple_list_item_activated_1);
        setListAdapter(adapter);
    }

    /**
     * item点击事件
     */
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        Toast.makeText(getApplicationContext(), ((TextView) v).getText(), Toast.LENGTH_SHORT).show();
    }
}

```**ListViewActivity3**





<div class="se-preview-section-delimiter"></div>

这里写代码片
“`

package com.sjm.gridviewAndListview;

import com.sjm.gridview.R;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ListViewActivity3 extends Activity {

    private ListView lv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setContentView(R.layout.listview3_layout);

        lv = (ListView) findViewById(R.id.lv);

        String arr[] = getResources().getStringArray(R.array.name);

        // 单选模式
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice,
                arr);
        lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

        // 多选模式
        // ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
        // android.R.layout.simple_list_item_multiple_choice, arr);
        // lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

        lv.setAdapter(adapter);

    }

}

```**ListViewNotifyDataSetChanged**
package com.sjm.gridviewAndListview;

import java.util.Vector;
import java.util.logging.LogRecord;

import com.sjm.gridview.R;
import com.sjm.gridview.entity.News;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

/**
 * listview 分页加载
 * 
 * @author sjm
 *
 */
public class ListViewNotifyDataSetChanged extends Activity implements OnScrollListener {

    private ListView lv_listview;

    private Vector<News> news = new Vector<News>();

    private MyAdapter myAdapter;

    /** 数据更新完成之后的标记 */
    private static final int DATA_UPDATE = 0x1;// Ctrl+Shift+X Ctrl+Shift+Y

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.notifydatasetchanged_layout);

        lv_listview = (ListView) findViewById(R.id.lv_listview);

        /** 滚动监听 */
        lv_listview.setOnScrollListener(this);

        /** 加载尾部 布局 */
        View footerView = getLayoutInflater().inflate(R.layout.loading, null);
        // lv_listview.addHeaderView(headerView);
        lv_listview.addFooterView(footerView);

        initData();

        myAdapter = new MyAdapter();
        lv_listview.setAdapter(myAdapter);
    }

    private int index = 1;

    /**
     * 初始化数据
     */
    private void initData() {
        for (int i = 0; i < 100; i++) {
            News n = new News();
            n.setTitle("title--" + index);
            n.setContent("content--" + index);
            index++;
            news.add(n);
        }
    }

    /**
     * 线程之间通讯的机制
     */
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
            case DATA_UPDATE:
                myAdapter.notifyDataSetChanged();
                break;
            }
        };
    };

    /**
     * 开线程模拟加载数据
     * 
     * @author sjm
     *
     */
    class LoadDataThread extends Thread {

        @Override
        public void run() {
            initData();
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // myAdapter.notifyDataSetChanged();

            // 通过handler给主线程发送消息标记
            handler.sendEmptyMessage(DATA_UPDATE);
        }
    }

    /**
     * 自定义适配器
     * 
     * @author sjm
     *
     */
    class MyAdapter extends BaseAdapter {

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

        @Override
        public Object getItem(int position) {
            return news.get(position);
        }

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder vh = null;

            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.notifydatasetchanged_item, null);

                vh = new ViewHolder();
                vh.tv_content = (TextView) convertView.findViewById(R.id.tv_content);
                vh.tv_title = (TextView) convertView.findViewById(R.id.tv_title);

                convertView.setTag(vh);
            } else {
                vh = (ViewHolder) convertView.getTag();
            }

            News n = news.get(position);
            vh.tv_title.setText(n.getTitle());
            vh.tv_content.setText(n.getContent());
            return convertView;
        }

        class ViewHolder {
            TextView tv_title;
            TextView tv_content;
        }

    }

    private int visibleLastIndex;// 可显示的最后一条数据的索引值

    /**
     * 滚动状态:SCROLL_STATE_FLING:正在滚动 SCROLL_STATE_IDLE:没有滚动,空闲 TOUCH_SCROLL:在滚动条上
     * 
     * @param view
     * @param scrollState
     */
    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (myAdapter.getCount() == visibleLastIndex && scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
            new LoadDataThread().start();
        }
    }

    /**
     * 正在滚动
     * 
     * @param view
     * @param firstVisibleItem
     *            第一条数据
     * @param visibleItemCount
     *            总数据
     * @param totalItemCount
     * 
     */
    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        visibleLastIndex = firstVisibleItem + visibleItemCount - 1;
    }
}
**实体类    News**





<div class="se-preview-section-delimiter"></div>

这里写代码片
“`

package com.sjm.gridview.entity;

/**
 * 
 * @author sjm
 *
 */
public class News {

    private String title;
    private String content;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

}

ExpandableListviewActivity

package com.sjm.expandableListview;

import com.sjm.gridview.R;

import android.app.Activity;
import android.app.ExpandableListActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
* 可扩展的listview :ExpandableListView
*
* @author sjm
*
*/
public class ExpandableListviewActivity extends Activity {

private ExpandableListView expandableListview;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.expandablel_layout);

    expandableListview = (ExpandableListView) findViewById(R.id.expandableListview);

    expandableListview.setAdapter(new MyExpandableAdapter());

    /**
     * 点击子item事件
     */
    expandableListview.setOnChildClickListener(new OnChildClickListener() {

        @Override
        public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition,
                long id) {
            Toast.makeText(getApplicationContext(), childs[groupPosition][childPosition], Toast.LENGTH_SHORT)
                    .show();
            return true;
        }
    });
}

private static String groups[] = { "好友", "黑名单" };

private static String childs[][] = { { "老大", "老二"}, { "老三", "老四" } };

/**
 * 适配器
 * 
 * @author sjm
 *
 */
class MyExpandableAdapter extends BaseExpandableListAdapter {

    /**
     * 组的总数----------->也就是父item的长度
     */
    @Override
    public int getGroupCount() {
        return groups.length;
    }

    /**
     * 子类的总数----->子item的长度
     */
    @Override
    public int getChildrenCount(int groupPosition) {
        return childs.length;
    }

    /**
     * 获取父item的每一个位置
     */
    @Override
    public Object getGroup(int groupPosition) {
        return groups[groupPosition];
    }

    /**
     * 获取子item的每一个位置
     */
    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return childs[groupPosition][childPosition];
    }

    /**
     * 获取父item的每一个选项
     */
    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    /**
     * 获取子item的每一个选项
     */
    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public boolean hasStableIds() {
        // TODO Auto-generated method stub
        return false;
    }

    /**
     * 
     */
    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {

        GroupViewHolder vh;

        if (convertView == null) {
            convertView = getLayoutInflater().inflate(R.layout.expandable_group_layout, null);
            vh = new GroupViewHolder();
            vh.iv_icon = (ImageView) convertView.findViewById(R.id.iv_icon);
            vh.tv_title = (TextView) convertView.findViewById(R.id.tv_title);
            convertView.setTag(vh);

        } else {
            vh = (GroupViewHolder) convertView.getTag();
        }

        // vh.iv_icon.setImageResource(resId);
        vh.tv_title.setText(groups[groupPosition]);
        return convertView;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView,
            ViewGroup parent) {
        ChildViewHolder vh;

        if (convertView == null) {
            convertView = getLayoutInflater().inflate(R.layout.expandable_group_layout, null);
            vh = new ChildViewHolder();
            vh.iv_icon = (ImageView) convertView.findViewById(R.id.iv_icon);
            vh.tv_title = (TextView) convertView.findViewById(R.id.tv_title);
            convertView.setTag(vh);

        } else {
            vh = (ChildViewHolder) convertView.getTag();
        }

        // vh.iv_icon.setImageResource(resId);
        vh.tv_title.setText(childs[groupPosition][childPosition]);
        return convertView;
    }

    /**
     * 二级选项是否可以被选中
     */
    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }

    class GroupViewHolder {
        ImageView iv_icon;
        TextView tv_title;
    }

    class ChildViewHolder {
        ImageView iv_icon;
        TextView tv_title;
    }

}

}

xml
activity_main

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin" >

    <GridView
        android:id="@+id/gridView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:columnWidth="90dp"
        android:horizontalSpacing="10dp"
        android:numColumns="auto_fit"
        android:stretchMode="columnWidth"
        android:verticalSpacing="10dp" >
    </GridView>

</LinearLayout>

listview1_layout

<?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" >

    <ImageView
        android:id="@+id/iv_item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/sample_0" />

    <TextView
        android:id="@+id/tv_item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1" />

</LinearLayout>
```**loading**





<div class="se-preview-section-delimiter"></div>

这里写代码片
“`

<?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="horizontal"
    android:layout_marginTop="10dp"
    android:gravity="center_horizontal" >

    <ProgressBar
        android:id="@+id/progress_load"
        style="?android:attr/progressBarStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/tv_load"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="正在玩命加载中..."
        android:textAppearance="?android:attr/textAppearanceSmall" />

</LinearLayout>
```**notifydatasetchanged_item**





<div class="se-preview-section-delimiter"></div>

<?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="horizontal" >

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:text="title" />

    <TextView
        android:id="@+id/tv_content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:text="content" />

</LinearLayout>

notifydatasetchanged_layout

版权声明:本文为博主原创文章,未经博主允许不得转载。

个人PHP学习笔记(一)--基本语法

目录 基本语法 语句结构 函数 数组 面向对象的程序设计 字符串 正则表达式 常用函数 文件系统 图形图像处理 MySQL数据库 Cookie&Session 错误和异常 基本语法变量 由英文字母或下...
  • u013474558
  • u013474558
  • 2015年05月17日 10:23
  • 409

Linux学习笔记之——起始篇

摘要:学习笔记目录、方便以后回顾、没有什么捷径可走、不断的记录、总结、练习、coding、coding。...
  • chenghuaying
  • chenghuaying
  • 2014年03月31日 16:47
  • 4549

Android 笔记(个人总结)

往sd卡写数据 权限uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> tr...
  • qq_37614259
  • qq_37614259
  • 2017年07月07日 20:07
  • 98

Python个人学习笔记三

Python个人学习笔记三
  • bjtbjt
  • bjtbjt
  • 2014年09月15日 11:40
  • 2268

Android学习笔记十二之Android基础UI三

Android学习笔记十二之Android基础UI三
  • solo_talk
  • solo_talk
  • 2016年06月29日 16:47
  • 3651

Angular一点基础知识

js中的mvc          mvc设计模式,简单说来是将复杂的代码设计规范化,把应用的输入,处理,输出分开,M是指数据模型,V是指用户界面,C则是控制器。像我刚接触的SSH框架中,例如stru...
  • qq_21577869
  • qq_21577869
  • 2015年07月21日 17:31
  • 239

完整学习笔记之Android基础(详版)

欢迎使用Markdown编辑器写博客本Markdown编辑器使用StackEdit修改而来,用它写博客,将会带来全新的体验哦: Markdown和扩展Markdown简洁的语法 代码块高亮 图片链接和...
  • Liliqianbaidu
  • Liliqianbaidu
  • 2017年04月27日 14:48
  • 630

ceph学习小结

最近部署ceph,硬是挤时间研究了下ceph的相关的东西,下面主要是通过看别人的文章以及自己工作用到的的知识总结而成。这可以算是ceph的笔记吧。...
  • duankaifei
  • duankaifei
  • 2014年10月28日 23:40
  • 1138

Android之学习安卓每天成长笔记

8月7日 1 、安装了反编译工具 jad  net.sf.jadclipse_3.3.0.jar 或者在help install software http://feeling.sourceforge...
  • u011068702
  • u011068702
  • 2015年08月19日 11:26
  • 1132

安卓基础到入门学习(复习笔记)

一、Android 基本常识1、写 10 个简单的 linux 命令mkdir 创建文件夹 rmdir 删除文件夹 rm 删除文件 mv 移动文件 cp 拷贝文件 cat 查看文件 tail 查看文件...
  • android_ty
  • android_ty
  • 2016年05月06日 11:18
  • 1855
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:android 个人学习笔记------------GridView&ListView
举报原因:
原因补充:

(最多只允许输入30个字)