关闭

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

标签: listviewgridviewandroid
76人阅读 评论(0) 收藏 举报
分类:

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

1
0

猜你在找
【直播】机器学习&数据挖掘7周实训--韦玮
【套餐】系统集成项目管理工程师顺利通关--徐朋
【直播】3小时掌握Docker最佳实战-徐西宁
【套餐】机器学习系列套餐(算法+实战)--唐宇迪
【直播】计算机视觉原理及实战--屈教授
【套餐】微信订阅号+服务号Java版 v2.0--翟东平
【直播】机器学习之矩阵--黄博士
【套餐】微信订阅号+服务号Java版 v2.0--翟东平
【直播】机器学习之凸优化--马博士
【套餐】Javascript 设计模式实战--曾亮
查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:5674次
    • 积分:249
    • 等级:
    • 排名:千里之外
    • 原创:18篇
    • 转载:3篇
    • 译文:0篇
    • 评论:0条
    文章分类