1. 逻辑代码
1.1 MainActivity 类
package com.example.myapplication;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* A simple {@link Fragment} subclass.
* Use the {@link BlankFragment4#newInstance} factory method to
* create an instance of this fragment.
*/
public class BlankFragment4 extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private ImageView imageView;// 定义全局的 imageView
private TextView textView; // 昵称
public BlankFragment4() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment BlankFragment2.
*/
// TODO: Rename and change types and number of parameters
public static BlankFragment4 newInstance(String param1, String param2) {
BlankFragment4 fragment = new BlankFragment4();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
// 普遍用view
View view = inflater.inflate(R.layout.fragment_blank4, container, false);
// 普遍用view
// TODO 头像组件
ImageView img = view.findViewById(R.id.imageView);
img.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("tag","点击换头像");
// 弹出菜单框 选择从相机拍照 还是 选择图库
// context : 传入activity对象
// 使用方法 1.this在activity中 2.activity.this同1 3.在Fragment中使用getActivity()
AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
dialog.setItems(new String[]{"拍照", "相册"},
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 点击后,具体处理,
Log.i("tag","which " + which);
Log.i("tag","dialog " + dialog);
// 判断 which 从而判断用户点击的是第几个
if (which == 0) {
// 调用系统相机权限 弹出是否同意授权
requestPermissions(new String[]{
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE
},10);// 动态申请权限
} else if (which == 1) {
// 调用系统相机 直接打开
Intent intent = new Intent();
// ACTION_GET_CONTENT = "android.intent.action.GET_CONTENT"
intent.setAction(Intent.ACTION_PICK); // 设置跳转到相册
intent.setType("image/*"); // 设置类型 选图片
startActivityForResult(intent,3);
}
}
});
dialog.show();
}
});
// TODO 昵称行组件
// 获取昵称
textView = view.findViewById(R.id.save_nick_name);
LinearLayout linearLayout = view.findViewById(R.id.nick_name);
linearLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("tag","点击换昵称"); // 调试
Intent intent = new Intent(getActivity(), ChangeNickname.class);
// 跳转后,当返回时能返回数据
startActivityForResult(intent, 2);
}
});
// 全局的 imageView 从 fragment_blank4 实例 view 获取
imageView = view.findViewById(R.id.imageView);
return view;
}
// 动态权限回调 requestCode:10 上面的requestCode
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// TODO 相机activity
if (requestCode == 10) { // 系统相机申请权限返回10
// 判断用户是否同意, PERMISSION_GRANTED = 0 : =>同意
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// 调用相机activity
Intent intent = new Intent();
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE); // 参数="android.media.action.IMAGE_CAPTURE"
startActivityForResult(intent,1); // 相机获取的数据的返回值
}
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
// 相机activity返回
// 获取相机返回的图片 bitmap
assert data != null;
Bundle bundle = data.getExtras();
assert bundle != null; // 调试宏,只在debug模式下有效。如果不满足条件,就会出现断言
Bitmap bitmap = bundle.getParcelable("data");
//
imageView.setImageBitmap(bitmap);
} else if (requestCode == 3) {
// 获取相册返回的图片 uri对象
// 例子:uri = content://com.google.android.apps.photos.contentprovider/-1/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F22/ORIGINAL/NONE/609859626
Uri uri = data.getData();
imageView.setImageURI(uri);
}
}
}
2. 布局代码
2.1 XML 文件
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
tools:context=".BlankFragment2">
<!-- TODO: Update blank fragment layout -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="600dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="110dp"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:textSize="20dp"
android:text="头像"
android:gravity="left|center"
android:scaleType="fitXY"
android:padding="20dp"/>
<ImageView
android:id="@+id/imageView"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_gravity="center"
android:layout_margin="20dp"
android:src="@drawable/avatar" />
</LinearLayout>
<LinearLayout
android:id="@+id/nick_name"
android:layout_width="match_parent"
android:layout_height="110dp"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:textSize="20dp"
android:text="昵称"
android:gravity="left|center"
android:padding="20dp"
tools:ignore="RtlHardcoded" />
<TextView
android:id="@+id/save_nick_name"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:textSize="15dp"
android:text="小明"
android:gravity="right|center"
android:padding="20dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="110dp"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:textSize="20dp"
android:text="微信号"
android:gravity="left|center"
android:padding="20dp"/>
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="right|center"
android:padding="20dp"
android:text="xiaoming"
android:textSize="15dp" />
</LinearLayout>
</LinearLayout>
</FrameLayout>
3.配置代码
3.1 build.gradle 文件
apply plugin: 'com.android.application'
android {
compileSdkVersion 30
buildToolsVersion "30.0.2"
defaultConfig {
applicationId "com.example.myapplication"
minSdkVersion 16
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
// 指定当前项目的所有依赖关系:本地依赖、库依赖、远程依赖
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"]) // 本地依赖
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'androidx.navigation:navigation-fragment:2.1.0'
implementation 'androidx.navigation:navigation-ui:2.1.0'
testImplementation 'junit:junit:4.12' // 测试用例库
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}
3.2 AndroidManifest.xml 文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplication">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:networkSecurityConfig="@xml/network_config"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme.NoActionBar">
<activity android:name=".MainActivity3">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity2" />
<activity android:name=".MainActivity" />
</application>
<!-- 配置相机权限 -->
<uses-permission android:name="android.permission.CAMERA"/>
<!-- 配置相机权限 -->
</manifest>