gpt4 book ai didi

java - 自动刷新抽屉导航标题

转载 作者:行者123 更新时间:2023-11-30 04:56:20 27 4
gpt4 key购买 nike

当我编辑个人资料图片并将其正确保存在 fragment 中时,但我必须找到获取导航标题个人资料图片的方法来更新与我的 fragment 相同的个人资料图片。当抽屉导航打开时,我需要自动刷新导航标题中的个人资料图片。找了1个引用,但是没有明确的程序和解释。

Refresh Header in Navigation Drawer

布局图像-发生的问题

enter image description here

ProfileFragment.java

package com.example.imlproject.ui.admin_profile;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.media.Image;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.example.imlproject.Admin_Activity;
import com.example.imlproject.R;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;

import java.util.UUID;

import static android.app.Activity.RESULT_OK;


public
class ProfileFragment extends Fragment {

private ProfileViewModel profileViewModel;
private TextView companyName,companyRegisterNumber,email,ic;
private EditText address,username,description,businessHour,contact;
private ImageView profile_pic,admin_edit_profile_pic,admin_save_profile_pic;
private FrameLayout frameLayout1;
private String imageURL;
private FirebaseStorage storage;
private StorageReference storageReference;
private DatabaseReference reference;
private FirebaseAuth auth;
private FirebaseUser user;
View headview;
ImageView nav_admin_profile_pic;
NavigationView navigationView;
private static final int GalleryPick = 1;
Uri filePath;

public
View onCreateView (
@NonNull LayoutInflater inflater ,
ViewGroup container , Bundle savedInstanceState
) {
profileViewModel =
ViewModelProviders.of ( this ).get ( ProfileViewModel.class );
final View root = inflater.inflate ( R.layout.fragment_admin_profile , container , false );

profile_pic=(ImageView )root.findViewById(R.id.admin_profile_fragment_profile_pic) ;
admin_edit_profile_pic=(ImageView)root.findViewById(R.id.admin_profile_image_edit_icon) ;
admin_save_profile_pic=(ImageView )root.findViewById(R.id.admin_profile_image_save_icon) ;

address=(EditText )root.findViewById(R.id.admin_profile_fragment_address_textView);
businessHour=(EditText )root.findViewById(R.id.admin_profile_fragment_business_hour_textView);
contact=(EditText )root.findViewById(R.id.admin_profile_fragment_contact_textView);
description=(EditText )root.findViewById(R.id.admin_profile_fragment_description_textView);
username=(EditText )root.findViewById(R.id.admin_profile_fragment_username_textView);

companyName=(TextView )root.findViewById(R.id.admin_profile_fragment_company_name_textView);
companyRegisterNumber=(TextView )root.findViewById(R.id.admin_profile_fragment_company_register_number_textView);
email=(TextView )root.findViewById(R.id.admin_profile_fragment_email_textView);
ic=(TextView )root.findViewById(R.id.admin_profile_fragment_ic_textView);





frameLayout1 = (FrameLayout )root.findViewById(R.id.FrameLayout1);
profile_pic.setEnabled(false);



storage=FirebaseStorage.getInstance();
storageReference=storage.getReference();
auth=FirebaseAuth.getInstance();
user=auth.getCurrentUser();
reference=FirebaseDatabase.getInstance().getReference().child("Account").child(user.getUid());

//============================================================================================================================================================================
profile_pic.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){

CropImage.activity()
.setAspectRatio(1,1)
.setCropShape(CropImageView.CropShape.RECTANGLE)
.start(getContext(),ProfileFragment.this);

}
});
//============================================================================================================================================================================

//============================================================================================================================================================================
admin_edit_profile_pic.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
admin_edit_profile_pic.setVisibility(View.GONE);
admin_save_profile_pic.setVisibility(View.VISIBLE);
frameLayout1.setBackgroundColor(Color.RED);
profile_pic.setEnabled(true);
Toast.makeText(getContext(),"Click your profile image above to edit it",Toast.LENGTH_LONG).show();
}
});
//============================================================================================================================================================================

//============================================================================================================================================================================
admin_save_profile_pic.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){


uploadImage();
admin_edit_profile_pic.setVisibility(View.VISIBLE);
admin_save_profile_pic.setVisibility(View.GONE);
frameLayout1.setBackgroundColor(Color.WHITE);
profile_pic.setEnabled(false);


}
});
//============================================================================================================================================================================


//============================================================================================================================================================================
reference.addValueEventListener(new ValueEventListener(){
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot){
address.setText(dataSnapshot.child("address").getValue().toString());
businessHour.setText(dataSnapshot.child("businessHour").getValue().toString());
companyName.setText(dataSnapshot.child("companyName").getValue().toString());
companyRegisterNumber.setText(dataSnapshot.child("companyRegisterNumber").getValue().toString());
contact.setText(dataSnapshot.child("contact").getValue().toString());
description.setText(dataSnapshot.child("description").getValue().toString());
email.setText(dataSnapshot.child("email").getValue().toString());
ic.setText(dataSnapshot.child("ic").getValue().toString());
username.setText(dataSnapshot.child("username").getValue().toString());

imageURL=dataSnapshot.child("imageURL").getValue().toString();

StorageReference ref=FirebaseStorage.getInstance().getReferenceFromUrl(imageURL);

ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>(){
@Override
public void onSuccess(Uri uri){

Picasso.get().load(uri).resize(250,250).into(profile_pic);
Toast.makeText(getActivity(),"Image Loaded",Toast.LENGTH_SHORT).show();

}
});
}

@Override
public void onCancelled(@NonNull DatabaseError databaseError){
Toast.makeText(getActivity(),databaseError.getMessage(),Toast.LENGTH_SHORT).show();
}
});
//============================================================================================================================================================================
return root;
}


//============================================================================================================================================================================
private void uploadImage()
{
if(filePath!=null)
{
String imageid=UUID.randomUUID().toString();
StorageReference ref =storageReference.child("images/"+imageid);
ref.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getActivity(),"Upload to online storage Successfully",Toast.LENGTH_SHORT).show();

}
});
auth=FirebaseAuth.getInstance();
user=auth.getCurrentUser();
reference= FirebaseDatabase.getInstance().getReference().child("Account").child(user.getUid());
reference.child("imageURL").setValue("gs://iml-project-4ccff.appspot.com/images/"+imageid);


Toast.makeText(getActivity(),"Profile image saved",Toast.LENGTH_SHORT).show();

//============================================================================================================================================================================
//View headerView = root.inflateHeaderView(R.layout.nav_header_admin_);
//nav_admin_profile_pic=(ImageView)headerView.findViewById(R.id.admin_nav_imageView);
/* reference.addValueEventListener(new ValueEventListener(){
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot){

imageURL=dataSnapshot.child("imageURL").getValue().toString();

StorageReference ref=FirebaseStorage.getInstance().getReferenceFromUrl(imageURL);

ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>(){
@Override
public void onSuccess(Uri uri){

Picasso.get().load(uri).resize(250,250).into(nav_admin_profile_pic);
Toast.makeText(getActivity(),"Image Loaded",Toast.LENGTH_SHORT).show();

}
});
}

@Override
public void onCancelled(@NonNull DatabaseError databaseError){
Toast.makeText(getActivity(),databaseError.getMessage(),Toast.LENGTH_SHORT).show();
}
});*/
//============================================================================================================================================================================
}
}
//============================================================================================================================================================================


//============================================================================================================================================================================
@Override
public void onActivityResult(int requestCode,int resultCode,Intent data) {

if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == Activity.RESULT_OK ) {
Uri resultUri = result.getUri();
filePath = result.getUri();
profile_pic.setImageURI(resultUri);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
Toast.makeText(getContext(),"Error",Toast.LENGTH_LONG).show();
}
}


}
//============================================================================================================================================================================

}

Admin.Activity.java

package com.example.imlproject;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.squareup.picasso.Picasso;

import androidx.drawerlayout.widget.DrawerLayout;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class Admin_Activity extends AppCompatActivity{

private AppBarConfiguration mAppBarConfiguration;
ImageView nav_admin_profile_pic;
TextView nav_admin_username, nav_admin_email;
View headview;
String imageURL;
//============================================================================================================================================================================
FirebaseStorage storage;
StorageReference storageReference;
DatabaseReference reference;
FirebaseAuth auth;
FirebaseUser user;
ActionBarDrawerToggle mDrawerToggle;
//============================================================================================================================================================================

@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_);

storage=FirebaseStorage.getInstance();
storageReference=storage.getReference();

Toolbar toolbar=findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final DrawerLayout drawer=findViewById(R.id.drawer_layout);
NavigationView navigationView=findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration=new AppBarConfiguration.Builder(R.id.nav_admin_profile,R.id.nav_admin_upload_product,R.id.nav_admin_edit_product,R.id.nav_admin_delete_product,R.id.nav_admin_order_receive,R.id.nav_admin_unpaid_order,R.id.nav_admin_history).setDrawerLayout(drawer).build();
NavController navController=Navigation.findNavController(this,R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this,navController,mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView,navController);

headview=navigationView.getHeaderView(0);
nav_admin_profile_pic=headview.findViewById(R.id.admin_nav_imageView);
nav_admin_username=headview.findViewById(R.id.admin_nav_username);
nav_admin_email=headview.findViewById(R.id.admin_nav_email);
auth=FirebaseAuth.getInstance();
user=auth.getCurrentUser();
reference=FirebaseDatabase.getInstance().getReference().child("Account").child(user.getUid());

//============================================================================================================================================================================
reference.addValueEventListener(new ValueEventListener(){
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot){
nav_admin_email.setText(dataSnapshot.child("email").getValue().toString());
nav_admin_username.setText(dataSnapshot.child("username").getValue().toString());
imageURL=dataSnapshot.child("imageURL").getValue().toString();

StorageReference ref=FirebaseStorage.getInstance().getReferenceFromUrl(imageURL);

ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>(){
@Override
public void onSuccess(Uri uri){

Picasso.get().load(uri).resize(250,250).into(nav_admin_profile_pic);
Toast.makeText(getApplicationContext(),"Image Loaded",Toast.LENGTH_SHORT).show();

}
});
}

@Override
public void onCancelled(@NonNull DatabaseError databaseError){
Toast.makeText(getApplicationContext(),databaseError.getMessage(),Toast.LENGTH_SHORT).show();
}
});
//============================================================================================================================================================================


}



@Override
public boolean onCreateOptionsMenu(Menu menu){
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.admin_,menu);
return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.admin_logout:{
final AlertDialog.Builder builder=new AlertDialog.Builder(Admin_Activity.this);
builder.setTitle("Warning!!!");
builder.setMessage("Are you sure you want to logout your account?");
builder.setCancelable(true);
//============================================================================================================================================================================
builder.setPositiveButton("Yes",new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog,int which){
FirebaseAuth.getInstance().signOut();
Intent intent=new Intent(getApplicationContext(),login_activity.class);
startActivity(intent);
finish();
}
});
//============================================================================================================================================================================
builder.setNegativeButton("No",new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog,int which){
dialog.cancel();
}
});
//============================================================================================================================================================================
AlertDialog alertDialog=builder.create();
alertDialog.show();
break;
}

}

return super.onOptionsItemSelected(item);
}

@Override
public boolean onSupportNavigateUp(){
NavController navController=Navigation.findNavController(this,R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController,mAppBarConfiguration)||super.onSupportNavigateUp();
}

@Override
public void onBackPressed(){
final AlertDialog.Builder builder=new AlertDialog.Builder(Admin_Activity.this);
builder.setTitle("Warning!!!");
builder.setMessage("Are you sure you want to logout your account?");
builder.setCancelable(true);
//============================================================================================================================================================================
builder.setPositiveButton("Yes",new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog,int which){
FirebaseAuth.getInstance().signOut();
Intent intent=new Intent(getApplicationContext(),login_activity.class);
startActivity(intent);
finish();
}
});
//============================================================================================================================================================================
builder.setNegativeButton("No",new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog,int which){
dialog.cancel();
}
});
//============================================================================================================================================================================
AlertDialog alertDialog=builder.create();
alertDialog.show();

}


}

nav_header_admin_.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="@dimen/nav_header_height"
android:background="@drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:theme="@style/ThemeOverlay.AppCompat.Dark">

<ImageView
android:id="@+id/admin_nav_imageView"
android:layout_width="250px"
android:layout_height="250px"
android:contentDescription="@string/nav_header_desc"
android:paddingTop="@dimen/nav_header_vertical_spacing"
app:srcCompat="@mipmap/ic_launcher_round" />

<TextView
android:id="@+id/admin_nav_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:text="username"
android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

<TextView
android:id="@+id/admin_nav_email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="email" />

</LinearLayout>

activity_admin_.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout 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:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">

<include
layout="@layout/app_bar_admin_"
android:layout_width="match_parent"
android:layout_height="match_parent" />

<com.google.android.material.navigation.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_admin_"
app:menu="@menu/activity_admin__drawer" />

</androidx.drawerlayout.widget.DrawerLayout>

最佳答案

您可以在 fragment 中引用导航 View 的属性。因此,请在您的 ProfileFragment.java firebase 监听器中进行以下更改。

ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>(){
@Override
public void onSuccess(Uri uri){


Toast.makeText(getApplicationContext(),"Image Loaded",Toast.LENGTH_SHORT).show();

//declare a global variable to contain the uri to
//set in the drawable listener
globalDeclaredUri = uri;

}
});

ProfileFragment.java onCreate 应该监听抽屉 Activity 。确保 getActivity 不为空。

@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_);

storage=FirebaseStorage.getInstance();
storageReference=storage.getReference();

//your codes continues...

NavigationView navigationView =(NavigationView)getActivity().findViewById(R.id.nav_view);
View parentView = navigationView.getHeaderView(0);
ImageView navProfilePic = parentView.findViewById(R.id.admin_nav_imageView);

DrawerLayout mDrawerLayout = (DrawerLayout) getActivity().findViewById(R.id.drawer_layout);

NavigationView navigationView = (NavigationView) getActivity().findViewById(R.id.nav_view);
final View parentView = navigationView.getHeaderView(0);
final ImageView navProfilePic = parentView.findViewById(R.id.img_header_bg);

DrawerLayout mDrawerLayout = (DrawerLayout) getActivity().findViewById(R.id.drawer_layout);

mDrawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {

}

@Override
public void onDrawerOpened(View drawerView) {

}

@Override
public void onDrawerClosed(View drawerView) {

}

@Override
public void onDrawerStateChanged(int newState) {
Picasso.get()
.load(globalDeclaredUri)
.resize(250,250)
.into(navProfilePic);
}
});
}

关于java - 自动刷新抽屉导航标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59072245/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com