明白了,我们可以使用 Picasso
库来处理图片的加载和裁剪,使其显示为圆形。
首先,在项目的 build.gradle
文件中添加 Picasso 库的依赖:
dependencies {
implementation 'com.squareup.picasso:picasso:2.71828'
}
然后,在 SettingsFragment.java
中使用 Picasso
库加载和裁剪图片。
修改 SettingsFragment.java
:
package com.example.notesapp;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;
import jp.wasabeef.picasso.transformations.CropCircleTransformation;
import static android.app.Activity.RESULT_OK;
public class SettingsFragment extends Fragment {
private static final int PICK_IMAGE = 1;
private EditText nicknameEditText, passwordEditText, confirmPasswordEditText;
private Button saveButton, logoutButton;
private ImageView profileImageView;
private SQLiteDatabase db;
private String username;
private String profileImageUri;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_settings, container, false);
nicknameEditText = view.findViewById(R.id.nickname);
passwordEditText = view.findViewById(R.id.password);
confirmPasswordEditText = view.findViewById(R.id.confirmPassword);
saveButton = view.findViewById(R.id.save);
logoutButton = view.findViewById(R.id.logout);
profileImageView = view.findViewById(R.id.profile_image);
NotesDBHelper dbHelper = new NotesDBHelper(getActivity());
db = dbHelper.getWritableDatabase();
MainActivity activity = (MainActivity) getActivity();
if (activity != null) {
username = activity.getIntent().getStringExtra("username");
loadProfileImage();
}
profileImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pickImage();
}
});
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String nickname = nicknameEditText.getText().toString();
String password = passwordEditText.getText().toString();
String confirmPassword = confirmPasswordEditText.getText().toString();
if (!TextUtils.isEmpty(password) && !password.equals(confirmPassword)) {
Toast.makeText(getActivity(), "密码和确认密码不一致", Toast.LENGTH_SHORT).show();
return;
}
ContentValues values = new ContentValues();
if (!TextUtils.isEmpty(nickname)) {
values.put("nickname", nickname);
}
if (!TextUtils.isEmpty(password)) {
values.put("password", password);
}
if (profileImageUri != null) {
values.put("profile_image", profileImageUri);
}
if (values.size() > 0) {
db.update("users", values, "username=?", new String[]{username});
Toast.makeText(getActivity(), "信息已更新", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "没有要更新的信息", Toast.LENGTH_SHORT).show();
}
}
});
logoutButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), LoginActivity.class);
startActivity(intent);
if (getActivity() != null) {
getActivity().finish();
}
}
});
return view;
}
private void pickImage() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, PICK_IMAGE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
profileImageUri = selectedImage.toString();
Picasso.get().load(selectedImage).transform(new CropCircleTransformation()).into(profileImageView);
}
}
private void loadProfileImage() {
Cursor cursor = db.query("users", new String[]{"profile_image"}, "username=?", new String[]{username}, null, null, null);
if (cursor.moveToFirst()) {
profileImageUri = cursor.getString(cursor.getColumnIndex("profile_image"));
if (profileImageUri != null) {
Picasso.get().load(Uri.parse(profileImageUri)).transform(new CropCircleTransformation()).into(profileImageView);
}
}
cursor.close();
}
}
步骤4:更新布局文件
确保 fragment_settings.xml
中的 ImageView
包含正确的 id
:
修改 fragment_settings.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"
android:padding="16dp">
<ImageView
android:id="@+id/profile_image"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:layout_marginBottom="16dp"
android:src="@drawable/ic_profile" />
<EditText
android:id="@+id/nickname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="昵称" />
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="密码"
android:inputType="textPassword" />
<EditText
android:id="@+id/confirmPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="确认密码"
android:inputType="textPassword" />
<Button
android:id="@+id/save"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="保存" />
<Button
android:id="@+id/logout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="退出登录" />
</LinearLayout>
这样,通过 Picasso
库和 CropCircleTransformation
,用户上传的图片会被裁剪成圆形并显示在头像位置。完成这些更改后,您可以运行和测试应用程序。如果有任何问题或进一步需求,请告诉我!
步骤1:在 RegisterActivity.java
中增加密码规则验证
修改 RegisterActivity.java
:
package com.example.notesapp;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class RegisterActivity extends AppCompatActivity {
private EditText usernameEditText, passwordEditText, confirmPasswordEditText;
private Button registerButton;
private SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
usernameEditText = findViewById(R.id.username);
passwordEditText = findViewById(R.id.password);
confirmPasswordEditText = findViewById(R.id.confirmPassword);
registerButton = findViewById(R.id.register);
// 初始化数据库
NotesDBHelper dbHelper = new NotesDBHelper(this);
db = dbHelper.getWritableDatabase();
registerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = usernameEditText.getText().toString();
String password = passwordEditText.getText().toString();
String confirmPassword = confirmPasswordEditText.getText().toString();
if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password) || TextUtils.isEmpty(confirmPassword)) {
Toast.makeText(RegisterActivity.this, "所有字段均为必填项", Toast.LENGTH_SHORT).show();
return;
}
if (!isValidPassword(password)) {
Toast.makeText(RegisterActivity.this, "密码必须不少于八个字符,且包含字母和数字", Toast.LENGTH_SHORT).show();
return;
}
if (!password.equals(confirmPassword)) {
Toast.makeText(RegisterActivity.this, "密码和确认密码不一致", Toast.LENGTH_SHORT).show();
return;
}
if (isUserExist(username)) {
Toast.makeText(RegisterActivity.this, "用户名已存在", Toast.LENGTH_SHORT).show();
return;
}
registerUser(username, password);
Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
finish();
}
});
}
private boolean isValidPassword(String password) {
if (password.length() < 8) {
return false;
}
boolean hasLetter = false;
boolean hasDigit = false;
for (char c : password.toCharArray()) {
if (Character.isLetter(c)) {
hasLetter = true;
} else if (Character.isDigit(c)) {
hasDigit = true;
}
if (hasLetter && hasDigit) {
return true;
}
}
return false;
}
private boolean isUserExist(String username) {
Cursor cursor = db.query("users", null, "username=?", new String[]{username}, null, null, null);
boolean exists = cursor.getCount() > 0;
cursor.close();
return exists;
}
private void registerUser(String username, String password) {
ContentValues values = new ContentValues();
values.put("username", username);
values.put("password", password);
db.insert("users", null, values);
}
}
步骤2:在 SettingsFragment.java
中增加密码规则验证
修改 SettingsFragment.java
:
package com.example.notesapp;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.squareup.picasso.Picasso;
import jp.wasabeef.picasso.transformations.CropCircleTransformation;
import static android.app.Activity.RESULT_OK;
public class SettingsFragment extends Fragment {
private static final int PICK_IMAGE = 1;
private EditText nicknameEditText, passwordEditText, confirmPasswordEditText;
private Button saveButton, logoutButton;
private ImageView profileImageView;
private SQLiteDatabase db;
private String username;
private String profileImageUri;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_settings, container, false);
nicknameEditText = view.findViewById(R.id.nickname);
passwordEditText = view.findViewById(R.id.password);
confirmPasswordEditText = view.findViewById(R.id.confirmPassword);
saveButton = view.findViewById(R.id.save);
logoutButton = view.findViewById(R.id.logout);
profileImageView = view.findViewById(R.id.profile_image);
NotesDBHelper dbHelper = new NotesDBHelper(getActivity());
db = dbHelper.getWritableDatabase();
MainActivity activity = (MainActivity) getActivity();
if (activity != null) {
username = activity.getIntent().getStringExtra("username");
loadProfileImage();
}
profileImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pickImage();
}
});
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String nickname = nicknameEditText.getText().toString();
String password = passwordEditText.getText().toString();
String confirmPassword = confirmPasswordEditText.getText().toString();
if (!TextUtils.isEmpty(password) && !isValidPassword(password)) {
Toast.makeText(getActivity(), "密码必须不少于八个字符,且包含字母和数字", Toast.LENGTH_SHORT).show();
return;
}
if (!TextUtils.isEmpty(password) && !password.equals(confirmPassword)) {
Toast.makeText(getActivity(), "密码和确认密码不一致", Toast.LENGTH_SHORT).show();
return;
}
ContentValues values = new ContentValues();
if (!TextUtils.isEmpty(nickname)) {
values.put("nickname", nickname);
}
if (!TextUtils.isEmpty(password)) {
values.put("password", password);
}
if (profileImageUri != null) {
values.put("profile_image", profileImageUri);
}
if (values.size() > 0) {
db.update("users", values, "username=?", new String[]{username});
Toast.makeText(getActivity(), "信息已更新", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "没有要更新的信息", Toast.LENGTH_SHORT).show();
}
}
});
logoutButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), LoginActivity.class);
startActivity(intent);
if (getActivity() != null) {
getActivity().finish();
}
}
});
return view;
}
private boolean isValidPassword(String password) {
if (password.length() < 8) {
return false;
}
boolean hasLetter = false;
boolean hasDigit = false;
for (char c : password.toCharArray()) {
if (Character.isLetter(c)) {
hasLetter = true;
} else if (Character.isDigit(c)) {
hasDigit = true;
}
if (hasLetter && hasDigit) {
return true;
}
}
return false;
}
private void pickImage() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, PICK_IMAGE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
profileImageUri = selectedImage.toString();
Picasso.get().load(selectedImage).transform(new CropCircleTransformation()).into(profileImageView);
}
}
private void loadProfileImage() {
Cursor cursor = db.query("users", new String[]{"profile_image"}, "username=?", new String[]{username}, null, null, null);
if (cursor.moveToFirst()) {
profileImageUri = cursor.getString(cursor.getColumnIndex("profile_image"));
if (profileImageUri != null) {
Picasso.get().load(Uri.parse(profileImageUri)).transform(new CropCircleTransformation()).into(profileImageView);
}
}
cursor.close();
}
}
通过这些更改,用户在注册和更新密码时将需要遵循密码规则:不少于八个字符,并且包含字母和数字。
步骤1:创建圆形图片转换类
首先,我们需要创建一个自定义的 Transformation
类,用于将图像显示为圆形。
创建 CircleTransform.java
:
package com.example.notesapp;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import com.squareup.picasso.Transformation;
public class CircleTransform implements Transformation {
@Override
public Bitmap transform(Bitmap source) {
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size);
if (squaredBitmap != source) {
source.recycle();
}
Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig());
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
BitmapShader shader = new BitmapShader(squaredBitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
paint.setShader(shader);
paint.setAntiAlias(true);
float r = size / 2f;
canvas.drawCircle(r, r, r, paint);
squaredBitmap.recycle();
return bitmap;
}
@Override
public String key() {
return "circle";
}
}
步骤2:在 SettingsFragment.java
中使用自定义转换类
修改 SettingsFragment.java
:
package com.example.notesapp;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.squareup.picasso.Picasso;
import static android.app.Activity.RESULT_OK;
public class SettingsFragment extends Fragment {
private static final int PICK_IMAGE = 1;
private EditText nicknameEditText, passwordEditText, confirmPasswordEditText;
private Button saveButton, logoutButton;
private ImageView profileImageView;
private SQLiteDatabase db;
private String username;
private String profileImageUri;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_settings, container, false);
nicknameEditText = view.findViewById(R.id.nickname);
passwordEditText = view.findViewById(R.id.password);
confirmPasswordEditText = view.findViewById(R.id.confirmPassword);
saveButton = view.findViewById(R.id.save);
logoutButton = view.findViewById(R.id.logout);
profileImageView = view.findViewById(R.id.profile_image);
NotesDBHelper dbHelper = new NotesDBHelper(getActivity());
db = dbHelper.getWritableDatabase();
MainActivity activity = (MainActivity) getActivity();
if (activity != null) {
username = activity.getIntent().getStringExtra("username");
loadProfileImage();
}
profileImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pickImage();
}
});
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String nickname = nicknameEditText.getText().toString();
String password = passwordEditText.getText().toString();
String confirmPassword = confirmPasswordEditText.getText().toString();
if (!TextUtils.isEmpty(password) && !isValidPassword(password)) {
Toast.makeText(getActivity(), "密码必须不少于八个字符,且包含字母和数字", Toast.LENGTH_SHORT).show();
return;
}
if (!TextUtils.isEmpty(password) && !password.equals(confirmPassword)) {
Toast.makeText(getActivity(), "密码和确认密码不一致", Toast.LENGTH_SHORT).show();
return;
}
ContentValues values = new ContentValues();
if (!TextUtils.isEmpty(nickname)) {
values.put("nickname", nickname);
}
if (!TextUtils.isEmpty(password)) {
values.put("password", password);
}
if (profileImageUri != null) {
values.put("profile_image", profileImageUri);
}
if (values.size() > 0) {
db.update("users", values, "username=?", new String[]{username});
Toast.makeText(getActivity(), "信息已更新", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "没有要更新的信息", Toast.LENGTH_SHORT).show();
}
}
});
logoutButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), LoginActivity.class);
startActivity(intent);
if (getActivity() != null) {
getActivity().finish();
}
}
});
return view;
}
private boolean isValidPassword(String password) {
if (password.length() < 8) {
return false;
}
boolean hasLetter = false;
boolean hasDigit = false;
for (char c : password.toCharArray()) {
if (Character.isLetter(c)) {
hasLetter = true;
} else if (Character.isDigit(c)) {
hasDigit = true;
}
if (hasLetter && hasDigit) {
return true;
}
}
return false;
}
private void pickImage() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, PICK_IMAGE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
profileImageUri = selectedImage.toString();
Picasso.get().load(selectedImage).transform(new CircleTransform()).into(profileImageView);
}
}
private void loadProfileImage() {
Cursor cursor = db.query("users", new String[]{"profile_image"}, "username=?", new String[]{username}, null, null, null);
if (cursor.moveToFirst()) {
profileImageUri = cursor.getString(cursor.getColumnIndex("profile_image"));
if (profileImageUri != null) {
Picasso.get().load(Uri.parse(profileImageUri)).transform(new CircleTransform()).into(profileImageView);
}
}
cursor.close();
}
}
步骤3:更新布局文件
确保 fragment_settings.xml
中的 ImageView
包含正确的 id
并调整其样式:
修改 fragment_settings.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"
android:padding="16dp">
<ImageView
android:id="@+id/profile_image"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:layout_marginBottom="16dp"
android:scaleType="centerCrop"
android:src="@drawable/ic_profile" />
<EditText
android:id="@+id/nickname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="昵称" />
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="密码"
android:inputType="textPassword" />
<EditText
android:id="@+id/confirmPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="确认密码"
android:inputType="textPassword" />
<Button
android:id="@+id/save"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="保存" />
<Button
android:id="@+id/logout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="退出登录" />
</LinearLayout>
步骤4:更新 build.gradle
确保 build.gradle
文件中包含 Picasso 库:
dependencies {
implementation 'com.squareup.picasso:picasso:2.71828'
}
完成这些更改后,用户上传的图片将显示为圆形头像,而不进行裁剪。请尝试运行和测试应用程序。如果有任何问题或进一步需求,请告诉我!
好的,我们可以使用 CardView
和 ImageView
来实现圆形头像效果。这种方法利用 CardView
的圆角属性来创建圆形头像。以下是具体的实现步骤。
步骤1:在布局文件中使用 CardView
和 ImageView
我们需要在 fragment_settings.xml
中添加一个 CardView
和 ImageView
,并设置 CardView
的圆角半径,使其成为一个圆形容器。
修改 fragment_settings.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"
android:padding="16dp">
<androidx.cardview.widget.CardView
android:id="@+id/profile_image_card"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_gravity="center"
android:layout_marginBottom="16dp"
android:radius="60dp"
android:elevation="4dp">
<ImageView
android:id="@+id/profile_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="@drawable/ic_profile" />
</androidx.cardview.widget.CardView>
<EditText
android:id="@+id/nickname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="昵称" />
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="密码"
android:inputType="textPassword" />
<EditText
android:id="@+id/confirmPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="确认密码"
android:inputType="textPassword" />
<Button
android:id="@+id/save"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="保存" />
<Button
android:id="@+id/logout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="退出登录" />
</LinearLayout>
步骤2:在 SettingsFragment.java
中加载图片
我们可以继续使用 Picasso
来加载图片,只需要对 ImageView
设置加载图片即可。
修改 SettingsFragment.java
:
package com.example.notesapp;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.squareup.picasso.Picasso;
import static android.app.Activity.RESULT_OK;
public class SettingsFragment extends Fragment {
private static final int PICK_IMAGE = 1;
private EditText nicknameEditText, passwordEditText, confirmPasswordEditText;
private Button saveButton, logoutButton;
private ImageView profileImageView;
private SQLiteDatabase db;
private String username;
private String profileImageUri;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_settings, container, false);
nicknameEditText = view.findViewById(R.id.nickname);
passwordEditText = view.findViewById(R.id.password);
confirmPasswordEditText = view.findViewById(R.id.confirmPassword);
saveButton = view.findViewById(R.id.save);
logoutButton = view.findViewById(R.id.logout);
profileImageView = view.findViewById(R.id.profile_image);
NotesDBHelper dbHelper = new NotesDBHelper(getActivity());
db = dbHelper.getWritableDatabase();
MainActivity activity = (MainActivity) getActivity();
if (activity != null) {
username = activity.getIntent().getStringExtra("username");
loadProfileImage();
}
profileImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pickImage();
}
});
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String nickname = nicknameEditText.getText().toString();
String password = passwordEditText.getText().toString();
String confirmPassword = confirmPasswordEditText.getText().toString();
if (!TextUtils.isEmpty(password) && !isValidPassword(password)) {
Toast.makeText(getActivity(), "密码必须不少于八个字符,且包含字母和数字", Toast.LENGTH_SHORT).show();
return;
}
if (!TextUtils.isEmpty(password) && !password.equals(confirmPassword)) {
Toast.makeText(getActivity(), "密码和确认密码不一致", Toast.LENGTH_SHORT).show();
return;
}
ContentValues values = new ContentValues();
if (!TextUtils.isEmpty(nickname)) {
values.put("nickname", nickname);
}
if (!TextUtils.isEmpty(password)) {
values.put("password", password);
}
if (profileImageUri != null) {
values.put("profile_image", profileImageUri);
}
if (values.size() > 0) {
db.update("users", values, "username=?", new String[]{username});
Toast.makeText(getActivity(), "信息已更新", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "没有要更新的信息", Toast.LENGTH_SHORT).show();
}
}
});
logoutButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), LoginActivity.class);
startActivity(intent);
if (getActivity() != null) {
getActivity().finish();
}
}
});
return view;
}
private boolean isValidPassword(String password) {
if (password.length() < 8) {
return false;
}
boolean hasLetter = false;
boolean hasDigit = false;
for (char c : password.toCharArray()) {
if (Character.isLetter(c)) {
hasLetter = true;
} else if (Character.isDigit(c)) {
hasDigit = true;
}
if (hasLetter && hasDigit) {
return true;
}
}
return false;
}
private void pickImage() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, PICK_IMAGE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
profileImageUri = selectedImage.toString();
Picasso.get().load(selectedImage).into(profileImageView);
}
}
private void loadProfileImage() {
Cursor cursor = db.query("users", new String[]{"profile_image"}, "username=?", new String[]{username}, null, null, null);
if (cursor.moveToFirst()) {
profileImageUri = cursor.getString(cursor.getColumnIndex("profile_image"));
if (profileImageUri != null) {
Picasso.get().load(Uri.parse(profileImageUri)).into(profileImageView);
}
}
cursor.close();
}
}
步骤3:确保 build.gradle
文件中包含 Picasso
库
dependencies {
implementation 'com.squareup.picasso:picasso:2.71828'
}
这样,通过使用 CardView
和 ImageView
的组合,并且利用 Picasso
来加载图片,我们实现了一个圆形头像的效果。请尝试运行和测试应用程序。如果有任何问题或进一步需求,请告诉我!