安卓入门学习笔记:GridView实现app勾选页面
Posted fanchenxinok
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了安卓入门学习笔记:GridView实现app勾选页面相关的知识,希望对你有一定的参考价值。
安卓studio开发环境的搭建推荐这个博客:https://blog.csdn.net/JerkSpan/article/details/85811265
花了两三天将java基础过了一遍,推荐廖雪峰老师的java基础教程:https://www.liaoxuefeng.com/wiki/1252599548343744
然后花了大概一周将安卓基础过了一遍,看得是“安卓开发入门教程:7天玩转安卓开发 ”:http://c.biancheng.net/android/
入门了接下来就需要自己实操下,想实现一个类似桌面launcher的界面,可以点击加号的图标添加app图标到这个界面。这里分享的是点击加号后进入app勾选界面的实现。效果如下:
点击图标勾选,再点击勾选图标变灰。
思路:这种布局毫无疑问是用Gridview控件来实现了,我想把原来的标题栏去掉,自己定制上图中的标题栏(有返回按钮,有提交按钮,还可以显示勾选了多少app),实现也很简单,
第一步:修改androidManifest.xml将原来的标题栏隐藏掉,并设置界面是横屏显示:
<activity android:name=".AppsGridActivity" android:screenOrientation="landscape" android:theme="@style/Theme.AppCompat.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</intent-filter>
</activity>
将界面用RelativeLayout布局分成上下两部分,上一部分放自己定制的标题栏,下部分放Gridview控件。布局XML(activity_apps_grid.xml)如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- 自己定制的标题栏部分 -->
<RelativeLayout
android:id="@+id/gridView_TitleBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:orientation="horizontal">
<ImageButton
android:id="@+id/griview_TitleBar_BackButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@mipmap/back" />
<TextView
android:id="@+id/griview_TitleBar_BackText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toEndOf="@id/griview_TitleBar_BackButton"
android:clickable="true"
android:text="返回"
android:textSize="24sp" />
<TextView
android:id="@+id/griview_TitleBar_Title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="应用列表"
android:textSize="24sp" />
<TextView
android:id="@+id/griview_TitleBar_Commit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:layout_marginEnd="20dip"
android:clickable="true"
android:text="提交"
android:textSize="24sp" />
</RelativeLayout>
<!-- 显示APP图标部分 -->
<GridView
android:id="@+id/gridView_showApps"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/gridView_TitleBar"
android:layout_marginTop="10dip"
android:columnWidth="90dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="5"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp">
</GridView>
</RelativeLayout>
Gridview每行显示5个Item。
第二步:界面整体布局配置好后,需要配置下GridView里面每个Item的内容了。每个Item需要显示APP的图标,包名,还要在右上角显示勾选的图标。所以一个Item里面包含三个控件,grid_item.xml内容如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="4dp">
<!-- APP图标 -->
<ImageView
android:id="@+id/AppIcon"
android:layout_width="60dip"
android:layout_height="60dip"
android:layout_centerHorizontal="true"></ImageView>
<!-- APP包的名称,位置在图标下面 -->
<TextView
android:id="@+id/AppName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/AppIcon"
android:layout_centerHorizontal="true"
android:layout_marginTop="6dip"
android:layout_marginBottom="6dip"
android:ellipsize="end"
android:maxEms="20"
android:singleLine="true"
android:text="app name"></TextView>
<!-- 勾选的图标,位置放置在APP图标的右上角 -->
<ImageView
android:id="@+id/AppCheck"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@id/AppIcon"
android:layout_alignRight="@id/AppIcon"
android:layout_alignParentTop="false"
android:layout_alignParentRight="false"
app:srcCompat="@mipmap/item_uncheck" />
</RelativeLayout>
上两步做完,整体布局就配置好了。
第三步:就是activity代码的实现了,我是用SimpleAdapter作为GridView控件的适配器,用法还是比较简单的,代码的注释也比较清楚了。代码如下:
/*************************************************
* 作者:范陈新
* 邮箱:531266381@qq.com
* 日期:2020-03-05
* 版本:Ver-01
**************************************************/
package com.example.android_learn;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.SimpleAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class AppsGridActivity extends AppCompatActivity
private SimpleAdapter gridItemAdapter;
private int appCheckCnt = 0;
private ArrayList<HashMap<String, Object>> listItemsFile = new ArrayList<HashMap<String, Object>>(); //用来保存配置文件的每个app的信息及选中状态
private ArrayList<HashMap<String, Object>> listItemsCur = new ArrayList<HashMap<String, Object>>(); //用来保存当前更新的每个app的信息及选中状态
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_apps_grid);
initGridView();
// 返回按钮的响应
ImageButton backButton = (ImageButton)findViewById(R.id.griview_TitleBar_BackButton);
backButton.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View view)
//将ListItemsSave的选中状态拷贝给listItems
for(int i = 0; i < listItemsFile.size(); i++)
HashMap<String, Object> item = (HashMap<String, Object>)listItemsFile.get(i);
Boolean pkg_check = (Boolean) item.get("ItemCheck");
listItemsCur.get(i).replace("ItemCheck", pkg_check);
Intent intent = new Intent();
intent.putExtra("return", "返回");
setResult(0, intent);
finish();
);
// 点击返回文本
TextView backText = (TextView)findViewById(R.id.griview_TitleBar_BackText);
backText.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View view)
//将ListItemsSave的选中状态拷贝给listItems
for(int i = 0; i < listItemsFile.size(); i++)
HashMap<String, Object> item = (HashMap<String, Object>)listItemsFile.get(i);
Boolean pkg_check = (Boolean) item.get("ItemCheck");
listItemsCur.get(i).replace("ItemCheck", pkg_check);
Intent intent = new Intent();
intent.putExtra("return", "返回");
setResult(0, intent);
finish();
);
//点击提交
TextView commitText = (TextView)findViewById(R.id.griview_TitleBar_Commit);
commitText.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View view)
for(int i = 0; i < listItemsCur.size(); i++)
HashMap<String, Object> item = (HashMap<String, Object>)listItemsCur.get(i);
String pkg_name = (String) item.get("ItemTitle");
Boolean pkg_check = (Boolean) item.get("ItemCheck");
setAppCheckState(pkg_name, pkg_check);
listItemsFile.get(i).replace("ItemCheck",pkg_check );
Intent intent = new Intent();
intent.putExtra("return", "提交");
setResult(0, intent);
finish();
);
private void initGridView()
//生成动态数组,并且转入数据
PackageManager pm = getPackageManager();
List<PackageInfo> installedPackages = pm.getInstalledPackages(0); // 获取所以已安装的包
String selfPkgName = getApplicationContext().getPackageName();
for (PackageInfo packageInfo : installedPackages)
String packageName = packageInfo.packageName; // 包名
ApplicationInfo applicationInfo = packageInfo.applicationInfo; // 应用信息
String name = applicationInfo.loadLabel(pm).toString(); // 应用名称
Drawable icon = applicationInfo.loadIcon(pm); // 应用图标
Boolean check = false;
System.out.println("@@@@@@@@name: "+name);
System.out.println("########packageName:"+packageName);
// 状态机,通过01状态来表示是否具备某些属性和功能
int flags = applicationInfo.flags; // 获取应用标记
if ((flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) == ApplicationInfo.FLAG_EXTERNAL_STORAGE)
//安装在sdcard
else
//安装在手机
if ((flags & ApplicationInfo.FLAG_SYSTEM) == ApplicationInfo.FLAG_SYSTEM)
//系统应用
System.out.println(name + "--->" + "系统应用");
else
//用户应用
System.out.println(name + "--->" + "用户应用");
if((name.startsWith("com.", 0) == false) && !selfPkgName.equals(packageName)) //过滤掉com.xx开头的包和本身
HashMap<String, Object> map = new HashMap<String, Object>();
check = getAppCheckState(name);
if(check == true)
appCheckCnt++;
map.put("ItemTitle", name); //包简称
map.put("ItemPkgName", packageName);
map.put("ItemImage", icon); //包的图标
map.put("ItemCheck", check); //是否被选中
listItemsCur.add(map);
listItemsFile = (ArrayList<HashMap<String, Object>>)listItemsCur.clone(); //复制
//修改标题栏内容
TextView titleContent = (TextView)findViewById(R.id.griview_TitleBar_Title);
titleContent.setText("添加应用到桌面("+ appCheckCnt + "/" + listItemsCur.size() + ")");
//生成适配器的ImageItem <====> 动态数组的元素,两者一一对应
gridItemAdapter = new SimpleAdapter(this,
listItemsCur, //数据来源
R.layout.grid_item, //grid_item的XML实现
//动态数组与ImageItem对应的子项
new String[] "ItemImage","ItemTitle","ItemCheck",
//ImageItem的XML文件里面的一个ImageView,两个TextView ID
new int[] R.id.AppIcon, R.id.AppName, R.id.AppCheck);
gridItemAdapter.setViewBinder(new SimpleAdapter.ViewBinder()
@Override
public boolean setViewValue(View view, Object data, String s)
if(view instanceof ImageView && data instanceof Drawable)
//设置APP图标ImageView数据源
ImageView iv = (ImageView)view;
iv.setImageDrawable((Drawable)data);
return true;
else if(view instanceof ImageView && data instanceof Boolean)
//设置是否勾选ImageView数据源
ImageView iv = (ImageView)view;
if((Boolean)data == true)
iv.setImageResource(R.mipmap.item_check);
else
iv.setImageResource(R.mipmap.item_uncheck);
return true;
else
return false;
);
final GridView gridView =(GridView)findViewById(R.id.gridView_showApps);
//添加并且显示
gridView.setAdapter(gridItemAdapter);
//添加消息处理
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener()
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
HashMap<String, Object> item = (HashMap<String, Object>) gridItemAdapter.getItem(position);
String packageName = (String)item.get("ItemPkgName");
System.out.println(packageName + " be clicked!");
int firstVisiblePos = gridView.getFirstVisiblePosition();
int lastVisiblePos = gridView.getLastVisiblePosition();
if(position >= firstVisiblePos && position <= lastVisiblePos)
View itemView = gridView.getChildAt(position - firstVisiblePos);
ImageView itemCheck = (ImageView) itemView.findViewById(R.id.AppCheck);
//点击勾选或取消勾选
if ((Boolean) item.get("ItemCheck") == false)
((HashMap<String, Object>) gridItemAdapter.getItem(position)).replace("ItemCheck", true);
itemCheck.setImageResource(R.mipmap.item_check);
appCheckCnt++;
TextView titleContent = (TextView)findViewById(R.id.griview_TitleBar_Title);
titleContent.setText("添加应用到桌面("+ appCheckCnt + "/" + listItemsCur.size() + ")");
else
((HashMap<String, Object>) gridItemAdapter.getItem(position)).replace("ItemCheck", false);
itemCheck.setImageResource(R.mipmap.item_uncheck);
appCheckCnt--;
TextView titleContent = (TextView)findViewById(R.id.griview_TitleBar_Title);
titleContent.setText("添加应用到桌面("+ appCheckCnt + "/" + listItemsCur.size() + ")");
);
//从代码包asserts目录下拷贝配置文件到/data/data/安装包名/
private void cpConfigFile()
try
InputStream in = getApplicationContext().getAssets().open("app_select.properties");
String path = "/data/data/" + getApplicationContext().getPackageName();
AppsConfigSetting.cpConfigFile(in, path);
catch (Exception e)
e.printStackTrace();
//从配置文件获取选中状态
private Boolean getAppCheckState(String pkg_name)
return AppsConfigSetting.getAppCheckState(pkg_name);
//保存状态到配置文件
private void setAppCheckState(String pkg_name, Boolean state)
AppsConfigSetting.setAppCheckState(pkg_name, state);
刚入门安卓开发,特此学习记录下,希望也对入门安卓开发的同学有帮助。
以上是关于安卓入门学习笔记:GridView实现app勾选页面的主要内容,如果未能解决你的问题,请参考以下文章
HarmonyOS鸿蒙学习笔记Tabs模仿安卓ViewPager+Fragment的效果
HarmonyOS鸿蒙学习笔记Tabs模仿安卓ViewPager+Fragment的效果