本文主要是介绍安卓入门学习笔记: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"><!-- 自己定制的标题栏部分 --><RelativeLayoutandroid:id="@+id/gridView_TitleBar"android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_marginTop="4dp"android:orientation="horizontal"><ImageButtonandroid:id="@+id/griview_TitleBar_BackButton"android:layout_width="wrap_content"android:layout_height="wrap_content"app:srcCompat="@mipmap/back" /><TextViewandroid: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" /><TextViewandroid:id="@+id/griview_TitleBar_Title"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerInParent="true"android:text="应用列表"android:textSize="24sp" /><TextViewandroid: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图标部分 --><GridViewandroid: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图标 --><ImageViewandroid:id="@+id/AppIcon"android:layout_width="60dip"android:layout_height="60dip"android:layout_centerHorizontal="true"></ImageView><!-- APP包的名称,位置在图标下面 --><TextViewandroid: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图标的右上角 --><ImageViewandroid: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的信息及选中状态@Overrideprotected 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() {@Overridepublic void onClick(View view) {//将ListItemsSave的选中状态拷贝给listItemsfor(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() {@Overridepublic void onClick(View view) {//将ListItemsSave的选中状态拷贝给listItemsfor(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() {@Overridepublic 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 IDnew int[] {R.id.AppIcon, R.id.AppName, R.id.AppCheck});gridItemAdapter.setViewBinder(new SimpleAdapter.ViewBinder() {@Overridepublic 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() {@Overridepublic 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勾选页面的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!