Android 天气APP(二十九)壁纸设置、图片查看、图片保存(1)

ApiService service = ServiceGenerator.createService(ApiService.class, 6);

service.getWallPaper().enqueue(new NetCallBack() {

@Override

public void onSuccess(Call call, Response response) {

if (getView() != null) {

getView().getWallPaperResult(response);

}

}

@Override

public void onFailed() {

if (getView() != null) {

getView().getDataFailed();

}

}

});

}

}

public interface IWallPaperView extends BaseView {

/**

  • 获取必应每日一图返回

  • @param response BiYingImgResponse

*/

void getBiYingResult(Response response);

/**

  • 壁纸数据返回

  • @param response WallPaperResponse

*/

void getWallPaperResult(Response response);

/**

  • 错误返回

*/

void getDataFailed();

}

}

订阅器也有了,现在回到WallPaperActivity ,继承MvpActivity,传入订阅器,然后实现里面的接口,代码如下:

package com.llw.goodweather.ui;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

import androidx.appcompat.widget.Toolbar;

import androidx.recyclerview.widget.RecyclerView;

import com.llw.goodweather.R;

import com.llw.goodweather.contract.WallPaperContract;

import com.llw.mvplibrary.bean.WallPaper;

import com.llw.mvplibrary.mvp.MvpActivity;

import butterknife.BindView;

import butterknife.ButterKnife;

import retrofit2.Response;

/**

  • 壁纸管理

  • @author llw

*/

public class WallPaperActivity extends MvpActivity<WallPaperContract.WallPaperPresenter> implements WallPaperContract.IWallPaperView {

@Override

public void initData(Bundle savedInstanceState) {

}

@Override

public int getLayoutId() {

return R.layout.activity_wall_paper;

}

@Override

protected WallPaperContract.WallPaperPresenter createPresent() {

return new WallPaperContract.WallPaperPresenter();

}

@Override

public void getBiYingResult(Response response) {

}

@Override

public void getWallPaperResult(Response response) {

}

@Override

public void getDataFailed() {

}

}

现在可以先不管这个Activity了,列表既然是显示壁纸,那么就需要一个item的布局,下面在app下的layout下面创建一个item_wallpaper_list.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:id=“@+id/item_wallpaper”

android:layout_height=“wrap_content”

android:layout_margin=“@dimen/dp_5”

android:orientation=“vertical”>

<com.google.android.material.imageview.ShapeableImageView

android:id=“@+id/iv_wallpaper”

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:scaleType=“centerCrop”

app:shapeAppearanceOverlay=“@style/roundedCornerStyle” />

你可能没有用过ShapeableImageView,没关系,首先在mvplibrary中的build.gradle中的dependencies闭包下新增一个依赖库

api ‘com.google.android.material:material:1.2.0’//更强

我之前的是1.1.0,那么你可以改成1.2.0。然后同步到你的项目中。你就可以是material专属的UI控件了,你可能会问为什么要用这个控件,普通的ImageView不行吗?因为普通的ImageView没有圆角啊,说道圆角图片我相信你不会陌生,你可能想到自定义ImageView来实现、或者使用第三方库来实现,但是ShapeableImageView里面就自带了圆角的样式给你,惊不惊喜意不意外?好了,废话不多少了,你的布局中应该还有报错的地方才对。因为你少了一个roundedCornerStyle的样式。在mvplibrary下的styles.xml中,新增一个样式就可以了。

可能你还注意到我这个item的高度是wrap_content,所以你看不到高度,那么为什么这样做呢?因为我要使用瀑布流,哪种错落感,会给用户不一样的体验,因为不设置高度,是因为需要动态设置ImageView的高度,来实现这个错落感。OK,下面该写这个Adapter了。在app的adapter包下新建一个WallPaperAdapter.java,相信这个代码你能看得懂。

package com.llw.goodweather.adapter;

import android.util.Log;

import android.view.ViewGroup;

import android.widget.LinearLayout;

import android.widget.RelativeLayout;

import androidx.annotation.Nullable;

import com.baidu.panosdk.plugin.indoor.util.ScreenUtils;

import com.bumptech.glide.Glide;

import com.chad.library.adapter.base.BaseQuickAdapter;

import com.chad.library.adapter.base.BaseViewHolder;

import com.google.android.material.imageview.ShapeableImageView;

import com.llw.goodweather.R;

import com.llw.goodweather.bean.WallPaperResponse;

import java.util.List;

/**

  • 壁纸列表适配器

  • @author llw

*/

public class WallPaperAdapter extends BaseQuickAdapter<WallPaperResponse.ResBean.VerticalBean, BaseViewHolder> {

//定义一个item的高度列表

List mHeightList;

/**

  • 头部广告

*/

private String Top = “top”;

/**

  • 底部广告

*/

private String Bottom = “bottom”;

public WallPaperAdapter(int layoutResId, @Nullable List<WallPaperResponse.ResBean.VerticalBean> data, List heightList) {

super(layoutResId, data);

this.mHeightList = heightList;

}

@Override

protected void convert(BaseViewHolder helper, WallPaperResponse.ResBean.VerticalBean item) {

ShapeableImageView imageView = helper.getView(R.id.iv_wallpaper);

//获取imageView的LayoutParams

RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) imageView.getLayoutParams();

layoutParams.height = dip2px(mHeightList.get(helper.getAdapterPosition()));

//重新设置imageView的高度

imageView.setLayoutParams(layoutParams);

if (Top.equals(item.getDesc()) || Bottom.equals(item.getDesc())) {

imageView.setImageResource(R.mipmap.icon_logo);

} else {

Glide.with(mContext).load(item.getImg()).into(imageView);

}

helper.addOnClickListener(R.id.item_wallpaper);

}

// dp 转成 px

private int dip2px(float dpVale) {

final float scale = mContext.getResources().getDisplayMetrics().density;

return (int) (dpVale * scale + 0.5f);

}

}

适配器也写完了,下面改渲染页面了,对不对。回到WallPaperActivity

/**

  • 标题

*/

@BindView(R.id.toolbar)

Toolbar toolbar;

/**

  • 数据列表

*/

@BindView(R.id.rv)

RecyclerView rv;

/**

  • AppBarLayout布局

*/

@BindView(R.id.appbar)

AppBarLayout appbar;

先绑定页面的控件,然后创建列表和适配器的对象

/**

  • 壁纸数据列表

*/

private List<WallPaperResponse.ResBean.VerticalBean> mList = new ArrayList<>();

/**

  • 壁纸数据适配器

*/

private WallPaperAdapter mAdapter;

/**

  • item高度列表

*/

private List heightList = new ArrayList<>();

/**

  • 壁纸数量

*/

private static final int WALLPAPER_NUM = 30;

/**

  • 头部和底部的item数据

*/

private WallPaperResponse.ResBean.VerticalBean topBean, bottomBean;

/**

  • 必应的每日壁纸

*/

private String biyingUrl = null;

新增一个初始化列表数据的方法。

/**

  • 初始化列表数据

*/

private void initWallPaperList() {

heightList.add(100);

for (int i = 0; i < WALLPAPER_NUM; i++) {

heightList.add(300);

}

heightList.add(100);

mAdapter = new WallPaperAdapter(R.layout.item_wallpaper_list, mList, heightList);

//瀑布流

StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);

//设置布局管理

rv.setLayoutManager(manager);

//设置数据适配器

rv.setAdapter(mAdapter);

//请求数据

mPresent.getWallPaper();

//获取必应壁纸

mPresent.biying();

mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {

@Override

public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

}

});

}

下面就该来处理返回的数据了。

/**

  • 必应壁纸数据返回

  • @param response BiYingImgResponse

*/

@Override

public void getBiYingResult(Response response) {

if (response.body().getImages() != null) {

//得到的图片地址是没有前缀的,所以加上前缀否则显示不出来

biyingUrl = “http://cn.bing.com” + response.body().getImages().get(0).getUrl();

Log.d(“type–>”, biyingUrl);

} else {

ToastUtils.showShortToast(context, “未获取到必应的图片”);

}

}

/**

  • 网络壁纸数据返回

  • @param response WallPaperResponse

*/

@Override

public void getWallPaperResult(Response response) {

if (response.body().getMsg().equals(Constant.SUCCESS)) {

List<WallPaperResponse.ResBean.VerticalBean> data = response.body().getRes().getVertical();

//创建头部和底部的两个广告item的假数据

topBean = new WallPaperResponse.ResBean.VerticalBean();

topBean.setDesc(“top”);

topBean.setImg(“”);

bottomBean = new WallPaperResponse.ResBean.VerticalBean();

bottomBean.setDesc(“bottom”);

bottomBean.setImg(“”);

//数据填充

if (data != null && data.size() > 0) {

mList.clear();

//添加头部

mList.add(topBean);

//添加主要数据

for (int i = 0; i < data.size(); i++) {

mList.add(data.get(i));

}

//添加尾部

mList.add(bottomBean);

Log.d(“list–>”, new Gson().toJson(mList));

//根据数据数量来刷新列表

mAdapter.notifyItemInserted(mList.size());

//删除数据库中的数据

LitePal.deleteAll(WallPaper.class);

for (int i = 0; i < mList.size(); i++) {

WallPaper wallPaper = new WallPaper();

wallPaper.setImgUrl(mList.get(i).getImg());

wallPaper.save();

}

dismissLoadingDialog();

} else {

ToastUtils.showShortToast(context, “壁纸数据为空”);

dismissLoadingDialog();

}

} else {

dismissLoadingDialog();

ToastUtils.showShortToast(context, “未获取到壁纸数据”);

}

}

@Override

public void getDataFailed() {

dismissLoadingDialog();

ToastUtils.showShortToast(context, “请求超时”);

}

Constant中增加一个

/**

  • 成功

*/

public static final String SUCCESS = “success”;

你会发现网络壁纸的返回处理有些麻烦。不过注释都有了,应该看得懂。下面在mvplibrary中创建WallPaper.java

在这里插入图片描述

里面的代码很简单:

package com.llw.mvplibrary.bean;

import org.litepal.crud.LitePalSupport;

import java.util.List;

/**

  • 壁纸表

  • @author llw

*/

public class WallPaper extends LitePalSupport {

private String ImgUrl;

public String getImgUrl() {

return ImgUrl;

}

public void setImgUrl(String imgUrl) {

ImgUrl = imgUrl;

}

}

然后改动assets下面的litepal.xml文件。

在这里插入图片描述

然后在WallPaperActivity的initData调用相关的方法。

@Override

public void initData(Bundle savedInstanceState) {

//加载弹窗

showLoadingDialog();

//高亮状态栏

StatusBarUtil.StatusBarLightMode(this);

//左上角的返回

Back(toolbar);

initWallPaperList();

}

下面请求就会有这个数据了,而且你上滑动就会有顶部的标题上隐藏的效果。

2. 浮动按钮的交互

下面加一个浮动按钮。在activity_wall_paper.xml中新增加一个

<com.google.android.material.floatingactionbutton.FloatingActionButton

android:id=“@+id/fab_setting”

android:layout_width=“wrap_content”

android:layout_height=“wrap_content”

android:layout_gravity=“end|bottom”

android:layout_margin=“@dimen/dp_20”

android:clickable=“true”

android:src=“@mipmap/icon_setting”

app:backgroundTint=“@color/white”

app:backgroundTintMode=“screen”

app:borderWidth=“@dimen/dp_0”

app:hoveredFocusedTranslationZ=“@dimen/dp_18”

app:pressedTranslationZ=“@dimen/dp_18”

app:rippleColor=“@color/blue_one” />

icon_setting的图标

在这里插入图片描述

然后在WallPaperActivity中新增

/**

  • 底部浮动按钮

*/

@BindView(R.id.fab_setting)

FloatingActionButton fabSetting;

然后在initWallPaperList方法中新增如下代码:

//滑动监听

rv.addOnScrollListener(new RecyclerView.OnScrollListener() {

@Override

public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {

super.onScrolled(recyclerView, dx, dy);

if (dy <= 0) {

fabSetting.show();

} else {//上滑

fabSetting.hide();

}

}

});

通过滑动RecyclerView对浮动按钮进行控制。当然浮动按钮要是光是显示和隐藏自然远远不行,浮动按钮点击之后要怎么样呢?

要出现一个底部弹窗,供你选择哪种方式的壁纸。

下面在app的layout下新建一个dialog_bottom_wallpaper_setting.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=“wrap_content”

android:background=“@color/white”

android:orientation=“vertical”>

<LinearLayout

android:id=“@+id/lay_wallpaper_list”

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:foreground=“?android:attr/selectableItemBackground”

android:gravity=“center”

android:orientation=“horizontal”

android:padding=“@dimen/dp_16”>

<TextView

android:layout_width=“0dp”

android:layout_height=“wrap_content”

android:layout_weight=“1”

android:text=“壁纸列表”

android:textColor=“@color/black_4”

android:textSize=“@dimen/sp_14” />

<ImageView

android:id=“@+id/iv_wallpaper_list”

android:layout_width=“@dimen/dp_24”

android:layout_height=“@dimen/dp_24”

android:src=“@mipmap/icon_selected”

android:visibility=“invisible” />

<View

android:layout_width=“match_parent”

android:layout_height=“1dp”

android:layout_marginLeft=“@dimen/dp_16”

android:layout_marginRight=“@dimen/dp_16”

android:background=“@color/gray_white_2” />

<LinearLayout

android:id=“@+id/lay_everyday_wallpaper”

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:foreground=“?android:attr/selectableItemBackground”

android:gravity=“center”

android:orientation=“horizontal”

android:padding=“@dimen/dp_16”>

<TextView

android:layout_width=“0dp”

android:layout_height=“wrap_content”

android:layout_weight=“1”

android:text=“每日一图”

android:textColor=“@color/black_4”

android:textSize=“@dimen/sp_14” />

<ImageView

android:id=“@+id/iv_everyday_wallpaper”

android:layout_width=“@dimen/dp_24”

android:layout_height=“@dimen/dp_24”

android:src=“@mipmap/icon_selected”

android:visibility=“invisible” />

<View

android:layout_width=“match_parent”

android:layout_height=“1dp”

android:layout_marginLeft=“@dimen/dp_16”

android:layout_marginRight=“@dimen/dp_16”

android:background=“@color/gray_white_2” />

<LinearLayout

android:id=“@+id/lay_upload_wallpaper”

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:foreground=“?android:attr/selectableItemBackground”

android:gravity=“center”

android:orientation=“horizontal”

android:padding=“@dimen/dp_16”>

<TextView

android:layout_width=“0dp”

android:layout_height=“wrap_content”

android:layout_weight=“1”

android:text=“手动上传”

android:textColor=“@color/black_4”

android:textSize=“@dimen/sp_14” />

<ImageView

android:id=“@+id/iv_upload_wallpaper”

android:layout_width=“@dimen/dp_24”

android:layout_height=“@dimen/dp_24”

android:src=“@mipmap/icon_selected”

android:visibility=“invisible” />

<View

android:layout_width=“match_parent”

android:layout_height=“1dp”

android:layout_marginLeft=“@dimen/dp_16”

android:layout_marginRight=“@dimen/dp_16”

android:background=“@color/gray_white_2” />

<LinearLayout

android:id=“@+id/lay_default_wallpaper”

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:foreground=“?android:attr/selectableItemBackground”

android:gravity=“center”

android:orientation=“horizontal”

android:padding=“@dimen/dp_16”>

<TextView

android:layout_width=“0dp”

android:layout_height=“wrap_content”

android:layout_weight=“1”

android:text=“默认壁纸”

android:textColor=“@color/black_4”

android:textSize=“@dimen/sp_14” />

<ImageView

android:id=“@+id/iv_default_wallpaper”

android:layout_width=“@dimen/dp_24”

android:layout_height=“@dimen/dp_24”

android:src=“@mipmap/icon_selected”

android:visibility=“invisible” />

预览如下:

在这里插入图片描述

icon_selected图标:

在这里插入图片描述

下面来写这个弹窗。

回到WallPaperActivity。

初始化这个弹窗,注意这个导包是我自定义的,不是系统自带的。

import com.llw.mvplibrary.view.dialog.AlertDialog;

/**

  • 底部弹窗

*/

AlertDialog bottomSettingDialog = null;

然后写一个方法用来显示弹窗以及里面的一些业务逻辑的处理。

/**

  • 壁纸底部弹窗弹窗

*/

private void showSettingDialog(int type) {

AlertDialog.Builder builder = new AlertDialog.Builder(context)

.addDefaultAnimation()//默认弹窗动画

.setCancelable(true)

.fromBottom(true)

//载入布局文件

.setContentView(R.layout.dialog_bottom_wallpaper_setting)

//设置弹窗宽高

.setWidthAndHeight(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)

//壁纸列表

.setOnClickListener(R.id.lay_wallpaper_list, v -> {

Intent intent = new Intent(context, ImageActivity.class);

intent.putExtra(“position”, 0);

startActivity(intent);

bottomSettingDialog.dismiss();

//每日一图

}).setOnClickListener(R.id.lay_everyday_wallpaper, v -> {

ToastUtils.showShortToast(context, “使用每日一图”);

SPUtils.putString(Constant.WALLPAPER_URL, biyingUrl, context);

//壁纸列表

SPUtils.putInt(Constant.WALLPAPER_TYPE, 2, context);

bottomSettingDialog.dismiss();

//手动上传

}).setOnClickListener(R.id.lay_upload_wallpaper, v -> {

startActivityForResult(CameraUtils.getSelectPhotoIntent(), SELECT_PHOTO);

ToastUtils.showShortToast(context, “请选择图片”);

bottomSettingDialog.dismiss();

//默认壁纸

}).setOnClickListener(R.id.lay_default_wallpaper, v -> {

ToastUtils.showShortToast(context, “使用默认壁纸”);

SPUtils.putInt(Constant.WALLPAPER_TYPE, 4, context);//使用默认壁纸

SPUtils.putString(Constant.WALLPAPER_URL, null, context);

bottomSettingDialog.dismiss();

});

bottomSettingDialog = builder.create();

ImageView iv_wallpaper_list = (ImageView) bottomSettingDialog.getView(R.id.iv_wallpaper_list);

ImageView iv_everyday_wallpaper = (ImageView) bottomSettingDialog.getView(R.id.iv_everyday_wallpaper);

ImageView iv_upload_wallpaper = (ImageView) bottomSettingDialog.getView(R.id.iv_upload_wallpaper);

ImageView iv_default_wallpaper = (ImageView) bottomSettingDialog.getView(R.id.iv_default_wallpaper);

switch (type) {

//壁纸列表

case 1:

iv_wallpaper_list.setVisibility(View.VISIBLE);

break;

//每日一图

case 2:

iv_everyday_wallpaper.setVisibility(View.VISIBLE);

break;

//手动上传

case 3:

iv_upload_wallpaper.setVisibility(View.VISIBLE);

break;

//默认壁纸

case 4:

iv_default_wallpaper.setVisibility(View.VISIBLE);

break;

default:

iv_default_wallpaper.setVisibility(View.GONE);

break;

}

bottomSettingDialog.show();

//弹窗关闭监听

bottomSettingDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {

@Override

public void onDismiss(DialogInterface dialog) {

fabSetting.show();

}

});

}

可以看到通过一个type来控制当前的壁纸属于那种模式,然后在弹窗关闭的时候显示浮动按钮,我在Constant中定义了两个变量,一个用于保存壁纸的状态,一个用于保存壁纸的地址值。

/**

  • 壁纸地址

*/

public static final String WALLPAPER_URL = “wallpaperUrl”;

/**

  • 壁纸类型 1 壁纸列表 2 每日一图 3 手动上传 4 默认壁纸

*/

public static final String WALLPAPER_TYPE = “wallpaperType”;

里面用到过一个工具类CameraUtils,代码如下:

package com.llw.goodweather.utils;

import android.annotation.TargetApi;

import android.content.ContentUris;

import android.content.ContentValues;

import android.content.Context;

import android.content.Intent;

import android.database.Cursor;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.graphics.Matrix;

import android.media.ExifInterface;

import android.net.Uri;

import android.os.Build;

import android.os.Environment;

import android.provider.DocumentsContract;

import android.provider.MediaStore;

import android.util.Log;

import android.widget.ImageView;

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.File;

import java.io.IOException;

/**

  • 相机、相册工具类

  • @author llw

*/

public class CameraUtils {

public static Intent getTakePhotoIntent(Context context, File outputImagepath) {

//获取系統版本

int currentapiVersion = Build.VERSION.SDK_INT;

// 激活相机

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

// 判断存储卡是否可以用,可用进行存储

if (hasSdcard()) {

if (currentapiVersion < 24) {

// 从文件中创建uri

Uri uri = Uri.fromFile(outputImagepath);

intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

} else {

//兼容android7.0 使用共享文件的形式

ContentValues contentValues = new ContentValues(1);

contentValues.put(MediaStore.Images.Media.DATA, outputImagepath.getAbsolutePath());

Uri uri = context.getApplicationContext().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);

intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

}

}

return intent;

}

public static Intent getSelectPhotoIntent() {

Intent intent = new Intent(“android.intent.action.GET_CONTENT”);

intent.setType(“image/*”);

return intent;

}

/*

  • 判断sdcard是否被挂载

*/

public static boolean hasSdcard() {

return Environment.getExternalStorageState().equals(

Environment.MEDIA_MOUNTED);

}

/**

  • 4.4及以上系统处理图片的方法

*/

@TargetApi(Build.VERSION_CODES.KITKAT)

public static String getImgeOnKitKatPath(Intent data, Context context) {

String imagePath = null;

Uri uri = data.getData();

Log.d(“uri=intent.getData :”, “” + uri);

if (DocumentsContract.isDocumentUri(context, uri)) {

String docId = DocumentsContract.getDocumentId(uri); //数据表里指定的行

Log.d(“getDocumentId(uri) :”, “” + docId);

Log.d(“uri.getAuthority() :”, “” + uri.getAuthority());

if (“com.android.providers.media.documents”.equals(uri.getAuthority())) {

String id = docId.split(“:”)[1];

String selection = MediaStore.Images.Media._ID + “=” + id;

imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection, context);

} else if (“com.android.providers.downloads.documents”.equals(uri.getAuthority())) {

Uri contentUri = ContentUris.withAppendedId(Uri.parse(“content://downloads/public_downloads”), Long.valueOf(docId));

imagePath = getImagePath(contentUri, null, context);

}

} else if (“content”.equalsIgnoreCase(uri.getScheme())) {

imagePath = getImagePath(uri, null, context);

}

return imagePath;

}

/**

  • 通过uri和selection来获取真实的图片路径,从相册获取图片时要用

*/

public static String getImagePath(Uri uri, String selection, Context context) {

String path = null;

Cursor cursor = context.getContentResolver().query(uri, null, selection, null, null);

if (cursor != null) {

if (cursor.moveToFirst()) {

path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));

}

cursor.close();

}

return path;

}

//改变拍完照后图片方向不正的问题

public static void ImgUpdateDirection(String filepath, Bitmap orc_bitmap, ImageView iv) {

int digree = 0;//图片旋转的角度

//根据图片的URI获取图片的绝对路径

Log.i(“tag”, “>>>>>>>>>>>>>开始”);

//String filepath = ImgUriDoString.getRealFilePath(getApplicationContext(), uri);

Log.i(“tag”, “》》》》》》》》》》》》》》》” + filepath);

//根据图片的filepath获取到一个ExifInterface的对象

ExifInterface exif = null;

try {

exif = new ExifInterface(filepath);

Log.i(“tag”, “exif》》》》》》》》》》》》》》》” + exif);

if (exif != null) {

// 读取图片中相机方向信息

int ori = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);

// 计算旋转角度

switch (ori) {

case ExifInterface.ORIENTATION_ROTATE_90:

digree = 90;

break;

case ExifInterface.ORIENTATION_ROTATE_180:

digree = 180;

break;

case ExifInterface.ORIENTATION_ROTATE_270:

digree = 270;

break;

default:

digree = 0;

break;

}

}

//如果图片不为0

if (digree != 0) {

// 旋转图片

Matrix m = new Matrix();

m.postRotate(digree);

orc_bitmap = Bitmap.createBitmap(orc_bitmap, 0, 0, orc_bitmap.getWidth(),

orc_bitmap.getHeight(), m, true);

}

if (orc_bitmap != null) {

iv.setImageBitmap(orc_bitmap);

}

} catch (IOException e) {

e.printStackTrace();

exif = null;

}

}

/**

  • 4.4以下系统处理图片的方法

*/

public static String getImageBeforeKitKatPath(Intent data, Context context) {

Uri uri = data.getData();

String imagePath = getImagePath(uri, null, context);

return imagePath;

}

//比例压缩

public static Bitmap comp(Bitmap image) {

ByteArrayOutputStream baos = new ByteArrayOutputStream();

image.compress(Bitmap.CompressFormat.JPEG, 100, baos);

if (baos.toByteArray().length / 1024 > 5120) {//判断如果图片大于5M,进行压缩避免在生成图片(BitmapFactory.decodeStream)时溢出

baos.reset();//重置baos即清空baos

image.compress(Bitmap.CompressFormat.JPEG, 50, baos);//这里压缩50%,把压缩后的数据存放到baos中

}

ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());

BitmapFactory.Options newOpts = new BitmapFactory.Options();

//开始读入图片,此时把options.inJustDecodeBounds 设回true了

newOpts.inJustDecodeBounds = true;

Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);

newOpts.inJustDecodeBounds = false;

int w = newOpts.outWidth;

int h = newOpts.outHeight;

//现在主流手机比较多是800*480分辨率,所以高和宽我们设置为

float hh = 800f;//这里设置高度为800f

float ww = 480f;//这里设置宽度为480f

//缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可

int be = 1;//be=1表示不缩放

if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放

be = (int) (newOpts.outWidth / ww);

} else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放

be = (int) (newOpts.outHeight / hh);

}

if (be <= 0)

be = 1;

newOpts.inSampleSize = be;//设置缩放比例

newOpts.inPreferredConfig = Bitmap.Config.RGB_565;//降低图片从ARGB888到RGB565

//重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了

isBm = new ByteArrayInputStream(baos.toByteArray());

bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);

return bitmap;//压缩好比例大小后再进行质量压缩

}

}

因为第三个是手动上传,所以会打开你的本地相册,当你选择一个图片之后,需要拿到返回的数据。所以要重写onActivityResult,在这个方法里面获取到图片的路径,然后放到缓存里,这时候你的壁纸类型就是手动上传的壁纸了。

/**

  • Activity返回结果

  • @param requestCode

  • @param resultCode

  • @param data

*/

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

super.onActivityResult(requestCode, resultCode, data);

switch (requestCode) {

//打开相册后返回

case SELECT_PHOTO:

if (resultCode == RESULT_OK) {

String imagePath = null;

//判断手机系统版本号

if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {

//4.4及以上系统使用这个方法处理图片

imagePath = CameraUtils.getImgeOnKitKatPath(data, this);

} else {

imagePath = CameraUtils.getImageBeforeKitKatPath(data, this);

}

displayImage(imagePath);

}

Log.d(“result–>”, requestCode + " " + resultCode + " " + data.getData().toString());

break;

default:

Log.d(“result–>”, requestCode + " " + resultCode + " " + data.getData().toString());

break;

}

}

/**

  • 从相册获取完图片(根据图片路径显示图片)

*/

private void displayImage(String imagePath) {

if (!TextUtils.isEmpty(imagePath)) {

//将本地上传选中的图片地址放入缓存,当手动定义开关打开时,取出缓存中的图片地址,显示为背景

SPUtils.putInt(Constant.WALLPAPER_TYPE, 3, context);

SPUtils.putString(Constant.WALLPAPER_URL, imagePath, context);

ToastUtils.showShortToast(context, “已更换为你选择的图片”);

} else {

SPUtils.putInt(Constant.WALLPAPER_TYPE, 0, context);

ToastUtils.showShortToast(context, “图片获取失败”);

}

}

至于默认壁纸,只要壁纸类型改为4,然后清空缓存中壁纸地址就可以了。因为这个地址是MainActivity中用来显示背景的依据,没有了就会显示默认背景。

至于第二个每日一图,就是在点击的时候把通过结果返回的地址拼接之后,再放入缓存中。同样指定类型。当然最头痛的是这个壁纸列表,首先在当前页面我们已经可以看到这个壁纸列表数据了。那么我们可以通过点击item的时候跳转到查看该壁纸完整的页面。所以需要创建一个ImageActivity,在app的UI包下创建。

布局的代码如下:

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

xmlns:tools=“http://schemas.android.com/tools”

android:layout_width=“match_parent”

android:layout_height=“match_parent”

android:background=“@color/white”

tools:context=“.ui.ImageActivity”>

<androidx.viewpager2.widget.ViewPager2

android:id=“@+id/vp”

android:layout_width=“match_parent”

android:layout_height=“match_parent”/>

<ImageView

android:id=“@+id/iv_back”

android:layout_width=“@dimen/dp_50”

android:layout_height=“@dimen/dp_50”

android:layout_marginLeft=“@dimen/dp_12”

android:layout_marginTop=“@dimen/dp_30”

android:padding=“@dimen/dp_8”

android:background=“@drawable/selector_bg_img”

android:src=“@mipmap/icon_image_return_white” />

<LinearLayout

android:layout_width=“wrap_content”

android:layout_height=“wrap_content”

android:layout_alignParentBottom=“true”

android:layout_centerHorizontal=“true”

android:layout_marginBottom=“@dimen/dp_12”

android:gravity=“center”

android:orientation=“horizontal”>

<com.google.android.material.button.MaterialButton

android:id=“@+id/btn_setting_wallpaper”

style=“@style/Widget.MaterialComponents.Button.UnelevatedButton”

android:layout_width=“@dimen/dp_100”

android:layout_height=“@dimen/dp_32”

android:layout_marginRight=“@dimen/dp_6”

android:insetTop=“@dimen/dp_0”

android:insetBottom=“@dimen/dp_0”

android:text=“设为壁纸”

android:theme=“@style/Theme.MaterialComponents.Light.NoActionBar”

app:backgroundTint=“@color/white_2”

app:cornerRadius=“@dimen/dp_16”

app:strokeColor=“@color/white”

app:strokeWidth=“@dimen/dp_1” />

<com.google.android.material.button.MaterialButton

android:id=“@+id/btn_download”

style=“@style/Widget.MaterialComponents.Button.UnelevatedButton”

android:layout_width=“@dimen/dp_100”

android:layout_height=“@dimen/dp_32”

android:layout_marginLeft=“@dimen/dp_6”

android:insetTop=“@dimen/dp_0”

android:insetBottom=“@dimen/dp_0”

android:text=“下载壁纸”

android:theme=“@style/Theme.MaterialComponents.Light.NoActionBar”

app:backgroundTint=“@color/about_bg_color”

app:cornerRadius=“@dimen/dp_16” />

因为布局用的是ViewPager2。它可以直接传RecyclerView.Adapter进去,让我们希望的是,进入之后可以左右滑动查看壁纸,所以用到这个,那么怎么实现呢?首先需要展示的item布局。在app下的layout中创建一个item_image_list.xml文件,里面的布局代码如下:

<?xml version="1.0" encoding="utf-8"?>

<com.google.android.material.imageview.ShapeableImageView xmlns:android=“http://schemas.android.com/apk/res/android”

android:id=“@+id/wallpaper”

android:scaleType=“centerCrop”

android:layout_width=“match_parent”

android:layout_height=“match_parent”/>

然后在ImageActivity中,需要继承BaseActivity。里面的完整代码如下:

package com.llw.goodweather.ui;

import android.content.Context;

import android.content.Intent;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.net.Uri;

import android.os.Bundle;

import android.os.Environment;

import android.provider.MediaStore;

import android.util.Log;

import android.view.View;

import android.widget.ImageView;

import androidx.annotation.Nullable;

import androidx.viewpager2.widget.ViewPager2;

import com.bumptech.glide.Glide;

import com.chad.library.adapter.base.BaseQuickAdapter;

import com.chad.library.adapter.base.BaseViewHolder;

import com.google.android.material.button.MaterialButton;

import com.google.gson.Gson;

import com.llw.goodweather.R;

import com.llw.goodweather.utils.Constant;

import com.llw.goodweather.utils.SPUtils;

import com.llw.goodweather.utils.StatusBarUtil;

import com.llw.goodweather.utils.ToastUtils;

import com.llw.mvplibrary.base.BaseActivity;

import com.llw.mvplibrary.bean.WallPaper;

import org.litepal.LitePal;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.URL;

import java.util.ArrayList;

import java.util.List;

import butterknife.BindView;

import butterknife.OnClick;

/**

  • 查看图片

  • @author llw

*/

public class ImageActivity extends BaseActivity {

@BindView(R.id.iv_back)

ImageView ivBack;

@BindView(R.id.btn_setting_wallpaper)

MaterialButton btnSettingWallpaper;

@BindView(R.id.btn_download)

MaterialButton btnDownload;

@BindView(R.id.vp)

ViewPager2 vp;

List mList = new ArrayList<>();

WallPaperAdapter mAdapter;

String wallpaperUrl = null;

private int position;

private Bitmap bitmap;

@Override

public void initData(Bundle savedInstanceState) {

showLoadingDialog();

//透明状态栏

StatusBarUtil.transparencyBar(context);

//获取位置

position = getIntent().getIntExtra(“position”, 0);

//获取数据

mList = LitePal.findAll(WallPaper.class);

Log.d(“list–>”, “” + mList.size());

if (mList != null && mList.size() > 0) {

for (int i = 0; i < mList.size(); i++) {

if (mList.get(i).getImgUrl().equals(“”)) {

mList.remove(i);

}

}

}

Log.d(“list–>”, “” + mList.size());

//RecyclerView实现方式

mAdapter = new WallPaperAdapter(R.layout.item_image_list, mList);

Log.d(“wallPaper”, new Gson().toJson(mList));

//ViewPager2实现方式

vp.setAdapter(mAdapter);

vp.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {

@Override

public void onPageSelected(int position) {

Log.d(“position–>”, “” + position);

wallpaperUrl = mList.get(position).getImgUrl();

bitmap = getBitMap(wallpaperUrl);

}

});

mAdapter.notifyDataSetChanged();

vp.setCurrentItem(position, false);

dismissLoadingDialog();

}

@Override

public int getLayoutId() {

return R.layout.activity_image;

}

@OnClick({R.id.iv_back, R.id.btn_setting_wallpaper, R.id.btn_download})

public void onViewClicked(View view) {

switch (view.getId()) {

case R.id.iv_back:

finish();

break;

//设置壁纸

case R.id.btn_setting_wallpaper:

//放入缓存

SPUtils.putString(Constant.WALLPAPER_URL, wallpaperUrl, context);

//壁纸列表

SPUtils.putInt(Constant.WALLPAPER_TYPE, 1, context);

ToastUtils.showShortToast(context, “已设置”);

break;

//下载壁纸

case R.id.btn_download:

saveImageToGallery(context, bitmap);

break;

default:

break;

}

}

/**

  • 壁纸适配器

*/

public class WallPaperAdapter extends BaseQuickAdapter<WallPaper, BaseViewHolder> {

public WallPaperAdapter(int layoutResId, @Nullable List data) {

super(layoutResId, data);

}

@Override

protected void convert(BaseViewHolder helper, WallPaper item) {

ImageView imageView = helper.getView(R.id.wallpaper);

Glide.with(mContext).load(item.getImgUrl()).into(imageView);

}

}

/**

  • 保存图片到本地相册

  • @param context 上下文

  • @param bitmap bitmap

  • @return

*/

public boolean saveImageToGallery(Context context, Bitmap bitmap) {
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数初中级Android工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则近万的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

img

img

img

img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

如果你觉得这些内容对你有帮助,可以扫码获取!!(备注:Android)

学习分享

在当下这个信息共享的时代,很多资源都可以在网络上找到,只取决于你愿不愿意找或是找的方法对不对了

很多朋友不是没有资料,大多都是有几十上百个G,但是杂乱无章,不知道怎么看从哪看起,甚至是看后就忘

如果大家觉得自己在网上找的资料非常杂乱、不成体系的话,我也分享一套给大家,比较系统,我平常自己也会经常研读。

2021最新上万页的大厂面试真题

七大模块学习资料:如NDK模块开发、Android框架体系架构…

只有系统,有方向的学习,才能在段时间内迅速提高自己的技术。

这份体系学习笔记,适应人群:
**第一,**学习知识比较碎片化,没有合理的学习路线与进阶方向。
**第二,**开发几年,不知道如何进阶更进一步,比较迷茫。
**第三,**到了合适的年纪,后续不知道该如何发展,转型管理,还是加强技术研究。

由于文章内容比较多,篇幅不允许,部分未展示内容以截图方式展示 。

《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》,点击传送门即可获取!

lic int getLayoutId() {

return R.layout.activity_image;

}

@OnClick({R.id.iv_back, R.id.btn_setting_wallpaper, R.id.btn_download})

public void onViewClicked(View view) {

switch (view.getId()) {

case R.id.iv_back:

finish();

break;

//设置壁纸

case R.id.btn_setting_wallpaper:

//放入缓存

SPUtils.putString(Constant.WALLPAPER_URL, wallpaperUrl, context);

//壁纸列表

SPUtils.putInt(Constant.WALLPAPER_TYPE, 1, context);

ToastUtils.showShortToast(context, “已设置”);

break;

//下载壁纸

case R.id.btn_download:

saveImageToGallery(context, bitmap);

break;

default:

break;

}

}

/**

  • 壁纸适配器

*/

public class WallPaperAdapter extends BaseQuickAdapter<WallPaper, BaseViewHolder> {

public WallPaperAdapter(int layoutResId, @Nullable List data) {

super(layoutResId, data);

}

@Override

protected void convert(BaseViewHolder helper, WallPaper item) {

ImageView imageView = helper.getView(R.id.wallpaper);

Glide.with(mContext).load(item.getImgUrl()).into(imageView);

}

}

/**

  • 保存图片到本地相册

  • @param context 上下文

  • @param bitmap bitmap

  • @return

*/

public boolean saveImageToGallery(Context context, Bitmap bitmap) {
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数初中级Android工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则近万的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

[外链图片转存中…(img-Qcji4iPP-1712154470219)]

[外链图片转存中…(img-3EL9Qv9U-1712154470220)]

[外链图片转存中…(img-egM1uX2z-1712154470220)]

[外链图片转存中…(img-7EnYj73H-1712154470220)]

[外链图片转存中…(img-iVY37MDR-1712154470221)]

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

如果你觉得这些内容对你有帮助,可以扫码获取!!(备注:Android)

学习分享

在当下这个信息共享的时代,很多资源都可以在网络上找到,只取决于你愿不愿意找或是找的方法对不对了

很多朋友不是没有资料,大多都是有几十上百个G,但是杂乱无章,不知道怎么看从哪看起,甚至是看后就忘

如果大家觉得自己在网上找的资料非常杂乱、不成体系的话,我也分享一套给大家,比较系统,我平常自己也会经常研读。

2021最新上万页的大厂面试真题

[外链图片转存中…(img-JRMreo6k-1712154470221)]

七大模块学习资料:如NDK模块开发、Android框架体系架构…

[外链图片转存中…(img-1ZStGHD6-1712154470221)]

只有系统,有方向的学习,才能在段时间内迅速提高自己的技术。

这份体系学习笔记,适应人群:
**第一,**学习知识比较碎片化,没有合理的学习路线与进阶方向。
**第二,**开发几年,不知道如何进阶更进一步,比较迷茫。
**第三,**到了合适的年纪,后续不知道该如何发展,转型管理,还是加强技术研究。

由于文章内容比较多,篇幅不允许,部分未展示内容以截图方式展示 。

《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》,点击传送门即可获取!
  • 11
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值