Android中利用ListView和GridView实现列表视图和网格(图标)视图的相互切换显示

想必大家在用电脑上网的时候,都会碰到过,文件的显示方式,一般有列表显示,图标显示,等显示方式。当然,android中也有这种显示方式。今天就来一起实现一下。
首先,说一下,刚开始因为项目需求,要有这个列表和网格来回切换显示的功能,没当回事,想着偷懒网上应该挺多,然后,找了大半天发现寥寥无几,唯独的一篇文章是写这个的,但是被转载了多次,都是相同的。可能原文作者只是提供了一个思路罢了,代码给的相当模糊。以至于被模糊的转载了好多次。打开一个连接发现一模一样,就连bug都一样。没办法,还是自己动手,丰衣足食吧。

先来看看实现后的真机效果图:

这里写图片描述

1.首先,是activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context="com.example.myfiledemo.MainActivity" >

        <Button
            android:id="@+id/btn_select_show"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" 
            android:gravity="center"
            android:text="切换视图"/>

        <GridView
            android:id="@+id/gridview1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:columnWidth="60dp"
            android:gravity="center"
            android:horizontalSpacing="10dp"
            android:numColumns="auto_fit"
            android:padding="10dp"
            android:stretchMode="columnWidth"
            android:verticalSpacing="10dp" />

        <ListView
            android:id="@+id/listview1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"/>

</LinearLayout>

布局也同样简单,一个ListView,一个GridView,还有一个可点击切换的Button.
这里GridView中的android:numColumns=”auto_fit”属性是根据手机屏幕会系统自动去设置显示列数,可适配平板。好了,关于GridView的使用属性,不是本篇博客的重点,想要了解的可自行查阅学习。

-

2.items.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" >

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

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

</LinearLayout>

items.xml也很简单,不知道你们都叫这个文件什么,我本人习惯叫模版

-

3.ManiActivity.java中


package com.example.myfiledemo;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.Toast;
/**
 * 视图切换  列表 网格
 * @author NanFeiLong
 *
 */
public class MainActivity extends Activity implements OnClickListener,
        OnItemClickListener {

    private boolean isShowView = true;
    private GridView mGridView;
    private ListView mListView;
    private ArrayList<MyBean> mArrayList;
    private Button mBtnSelectShow;
    private MyAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mListView = (ListView) findViewById(R.id.listview1);
        mGridView = (GridView) findViewById(R.id.gridview1);
        mBtnSelectShow = (Button) findViewById(R.id.btn_select_show);
        initdata();// 数据
        mBtnSelectShow.setOnClickListener(this);
        adapter = new MyAdapter(this, mArrayList);
        setLayout();

    }

    /**
     * 添加数据
     */
    private void initdata() {
        // TODO Auto-generated method stub
        mArrayList = new ArrayList<MyBean>();
        for (int i = 0; i < 20; i++) {
            mArrayList.add(new MyBean("项目"+i, R.drawable.format_folder));
        }
    }
        /**
         *实现切换视图
         */
    private void setLayout() {
        if (isShowView) {
            if (mGridView == null) {
                mGridView = (GridView) findViewById(R.id.gridview1);
            }
            mGridView.setVisibility(View.VISIBLE);
            mGridView.setAdapter(adapter);
            mGridView.setOnItemClickListener(this);
            mListView.setVisibility(View.GONE);
            mGridView.setSelection(0);
            isShowView = !isShowView;
        } else {
            if (mListView == null) {
                mListView = (ListView) findViewById(R.id.listview1);
            }
            mListView.setVisibility(View.VISIBLE);
            mListView.setAdapter(adapter);
            mListView.setOnItemClickListener(this);
            mGridView.setVisibility(View.GONE); 
            mListView.setSelection(0);//可将第一个item对我们可见显示,用于错乱,也可以不要
            isShowView = !isShowView;
        }
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.btn_select_show:
            setLayout();
            break;
        default:
            break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        // TODO Auto-generated method stub
        switch (parent.getId()) {
        case R.id.gridview1:
            Toast.makeText(MainActivity.this,
                    "gridview-" + mArrayList.get(position).getIconName(),
                    Toast.LENGTH_SHORT).show();
            break;
        case R.id.listview1:
            Toast.makeText(MainActivity.this,
                    "listview-" + mArrayList.get(position).getIconName(),
                    Toast.LENGTH_SHORT).show();
            break;
        default:
            break;
        }

    }

}

可以看到其中的一个核心方法setLayout()是实现的重点所在,当onCreate时候执行一次setLayout()方法,让其只显示一个,然后是每当点击一次button会执行一次setLayout()方法,显示就会在列表和网格视图之间切换一次,在其中我们设置了一个flag,isShowView。当setLayout()的最后利用isShowView = !isShowView;给其肤质,这样就会来回切换啦。

4. MyAdapter.java

package com.example.myfiledemo;

import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/**
 * 自定义BaseAdapter
 * @author NanFeiLong
 *
 */

public class MyAdapter extends BaseAdapter {

    private LayoutInflater mInflater = null;
    private Context mContext;
    private ArrayList<MyBean> mArrayList = null;

    public MyAdapter(Context context, ArrayList<MyBean> arrayList) {
        mContext = context;
        mArrayList = arrayList;
        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return mArrayList == null ? 0 : mArrayList.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return mArrayList == null ? null : mArrayList.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        ViewHolder holder = null;
        MyBean mBean = (MyBean) getItem(position);
        if (convertView == null) {
            convertView = mInflater.from(mContext).inflate(R.layout.items, parent, false);
            holder = new ViewHolder();
            holder.imageView = (ImageView) convertView.findViewById(R.id.imageView1);
            //holder.imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);    
            holder.textView = (TextView) convertView.findViewById(R.id.textView1);
            //注意这里是个坑,如果写在这里的话,listview中会出现item重复显示的bug,
            //本人当时由于写错了,在这里走了冤枉了,望读者能注意
            //holder.imageView.setImageResource(mBean.getImageId());
            //holder.textView.setText(mBean.getIconName());
            convertView.setTag(holder);
        }else {
             holder = (ViewHolder) convertView.getTag();
        }
        holder.imageView.setImageResource(mBean.getImageId());
        holder.textView.setText(mBean.getIconName());
        return convertView;
    }


    class ViewHolder {
        ImageView imageView;
        TextView textView;
    }  

}

5.最后还有一个自己定义的实体类MyBean.java,用于存储imageView和textView,

package com.example.myfiledemo;


/**
 * 实体类
 * @author NanFeiLong
 *
 */

public class MyBean {

    private String iconName; 
    private int  imageId;  

    public MyBean(String iconName, int imageId) {
        super();
        this.iconName = iconName;
        this.imageId = imageId;
    }

    public String getIconName() {
        return iconName;
    }

    public void setIconName(String iconName) {
        this.iconName = iconName;
    }

    public int getImageId() {
        return imageId;
    }

    public void setImageId(int imageId) {
        this.imageId = imageId;
    }


    @Override
    public String toString() {
        return "MyBean [iconName=" + iconName + ", imageId=" + imageId
                + ", getIconName()=" + getIconName() + ", getImageId()="
                + getImageId() + ", getClass()=" + getClass() + ", hashCode()="
                + hashCode() + ", toString()=" + super.toString() + "]";
    }












}

6.至此,算是结束了,运行之后,会出现如图的效果

  • 拓展一下,实际项目中,有可能列表布局和网格布局的items.xml都不同,可能还 有其他不同,这样的情况,可以写两个items.xml。虽然代码比较多,但是都是相同的。然后在setLayout()方法显示每一个的时候,在去new相对应的adapter。这里给出我自己项目中的一个实际应用

private void setLayout() {
        // TODO Auto-generated method stub
        if (isShowListView) {
            if (fileLv == null) {
                fileLv = (ListView) findViewById(R.id.listview);
            }
            fileLv.setVisibility(fileLv.VISIBLE);
            fileLv.setOnItemClickListener(this);
            fileGv.setVisibility(fileGv.GONE);
            sAdapter = new SimpleAdapter(this, aList, R.layout.listview_item,
                    new String[] { "fImg", "fName", "fInfo" }, new int[] {
                            R.id.file_img, R.id.file_name, R.id.file_info });
            fileLv.setAdapter(sAdapter);
            isShowListView = !isShowListView;
        } else {
            if (fileGv == null) {
                fileGv = (GridView) findViewById(R.id.gridview);
            }
            fileGv.setVisibility(fileGv.VISIBLE);
            fileGv.setOnItemClickListener(this);
            fileLv.setVisibility(fileLv.GONE);
            sAdapter = new SimpleAdapter(this, aList, R.layout.gridview_item,
                    new String[] { "fImg", "fName" }, new int[] {
                            R.id.iv_gridview, R.id.tv_name_gridview });
            fileGv.setAdapter(sAdapter);
            isShowListView = !isShowListView;
        }

    }

好了,到这里应该都没有疑问了。洗洗睡觉咯,祝各位大神好梦O(∩_∩)O~

源码

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 终极编程指南 设计师:CSDN官方博客 返回首页