关于片段生命周期

Posted

技术标签:

【中文标题】关于片段生命周期【英文标题】:About fragment life cycle 【发布时间】:2021-01-11 22:49:08 【问题描述】:

我的片段中有一些奇怪的东西,当活动重新启动或暂停时,片段没有响应我的 onClick 事件,这是我的代码,我应该怎么做才能不再遇到这个问题 提示这是一个注册片段,它将模型对象返回给活动 throw communicator,我希望任何人都可以帮助我


import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;

import com.gahez.gahez.Constants;
import com.gahez.gahez.Definer;
import com.gahez.gahez.R;
import com.gahez.gahez.activities.UserSignUpActivity;
import com.gahez.gahez.data_wrappers.Courier;
import com.gahez.gahez.fragments.interfaces.SignUpCommunicator;
import com.gahez.gahez.utilities.Utilities;

import java.io.File;
import java.io.IOException;

public class SignUpFragment extends Fragment implements View.OnClickListener, CompoundButton.OnCheckedChangeListener 


    private ImageView profilePicImageView;
    private ImageView showPasswordIMageView;
    private EditText passwordEditText;
    private EditText emailEditText;
    private EditText userNameEditText;
    private EditText phoneEditText;
    private EditText confirmPasswordEditText;
    private EditText nationalIdEditText;
    private Button signUpButton;
    private TextView addImageTextView;
    private CheckBox maleCheckBox;
    private CheckBox femaleCheckBox;
    private ConstraintLayout backgroundConstraintLayout;

    public Activity context;
    private Intent outComingIntent;
    private SignUpCommunicator communicator;

    private File userPhotoFile;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) 
        return inflater.inflate(R.layout.signup_fragment,container,false);
    

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) 
        super.onActivityCreated(savedInstanceState);
            setContext();
            setCommunicator();
            defineViews();
            setListeners();
            Definer.setupUI(backgroundConstraintLayout,context);

    


    //my methods
    //---------------------------------------------------------------------------------------------
    public void setListeners()
        signUpButton.setOnClickListener(this);
        maleCheckBox.setOnCheckedChangeListener(this);
        femaleCheckBox.setOnCheckedChangeListener(this);
        profilePicImageView.setOnClickListener(this);
    

    public void defineViews() 
        profilePicImageView =  context.findViewById(R.id.profile_pic);
        showPasswordIMageView =  context.findViewById(R.id.password_show);
        passwordEditText =context.findViewById(R.id.password);
        signUpButton=context.findViewById(R.id.next);
        emailEditText= context.findViewById(R.id.email);
        userNameEditText= context.findViewById(R.id.username);
        phoneEditText= context.findViewById(R.id.phone_number);
        confirmPasswordEditText= context.findViewById(R.id.conferim_password);
        backgroundConstraintLayout=context.findViewById(R.id.background_constraint_layout);
        addImageTextView = context.findViewById(R.id.add_image_text);
        maleCheckBox=context.findViewById(R.id.male_check_box);
        femaleCheckBox=context.findViewById(R.id.female_check_box);
        nationalIdEditText= context.findViewById(R.id.national_id_edit_text);
    

    public void setContext()
        context=getActivity();
    

    public void setCommunicator()
        this.communicator =(SignUpCommunicator) getActivity();
    

    public Courier getCourier()
        Courier courier = null;
        String email = emailEditText.getText().toString();
        String password = passwordEditText.getText().toString();
        String confirmationPassword = confirmPasswordEditText.getText().toString();
        String phoneNumber = phoneEditText.getText().toString();
        String userName = userNameEditText.getText().toString();
        String nationalId = nationalIdEditText.getText().toString();
        String gender = getGender();
        if(!email.equals("")&&!password.equals("")&&!confirmationPassword.equals("")&&
           !phoneNumber.equals("")&&!userName.equals("")&&!gender.equals("")&&!nationalId.equals(""))
            courier = new Courier("carrier",userName,email,password,phoneNumber,
                    gender,nationalId);
        return courier;  //it returns null if any field is empty
    

    public String getGender() 
        String gender="male";
        if(femaleCheckBox.isChecked())
            gender="female";
        return gender;
    

    public String validatePasswords()
        String password = passwordEditText.getText().toString();
        String confirmationPassword = confirmPasswordEditText.getText().toString();
        if(password.equals(confirmationPassword))
            if(password.length()>=8)
                return Constants.VALID_PASSWORD;
            else
                return Constants.SHORT_PASSWORD;
        else
            return Constants.NOT_MATCHING_PASSWORDS;
    

    public boolean isValidDataEntry(Courier courier)
        if(courier==null)  //if courier is null then the fun getCourier find one or more field empty
            Toast.makeText(context, getString(R.string.complete_your_data), Toast.LENGTH_SHORT).show();
            return false;
        else 
            if(!Definer.validateEmailAddress(emailEditText.getText().toString())) 
                Toast.makeText(context, getString(R.string.invaild_email_address), Toast.LENGTH_SHORT).show();
                return false;
            
            else 
                String passwordValidationResult = validatePasswords();
                if(passwordValidationResult.equals(Constants.SHORT_PASSWORD)) 
                    Toast.makeText(context, getString(R.string.password_must_be_eight_chars_at_least)
                            , Toast.LENGTH_SHORT).show();
                    return false;
                
                else if(passwordValidationResult.equals(Constants.NOT_MATCHING_PASSWORDS)) 
                    Toast.makeText(context,
                            getString(R.string.passwords_are_not_matching),
                            Toast.LENGTH_SHORT).show();
                    return false;
                
                else return true;

            
        
    

    public boolean checkStoragePermissions()
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED && ActivityCompat.
                checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) 
            requestPermissions(Constants.STORAGE_PERMISSIONS,Constants.EXTERNAL_STORAGE_PERMISSIONS_REQUEST_CODE);
            Log.d(Constants.LOG_TAG,"hello");
            return false;
        else
        
            return true;
        
    

    private void getImageFromDevice() 
        if(checkStoragePermissions()) 
            outComingIntent = new Intent(Intent.ACTION_GET_CONTENT);
            outComingIntent.setType("image/*");
            startActivityForResult(outComingIntent, Constants.PROFILE_IMAGE_REQUEST_CODE);
        
    


    //override methods
    //----------------------------------------------------------------------------------------------
    @Override
    public void onClick(View v) 
        switch (v.getId())
            case R.id.next:
                Courier courier = getCourier();
                if(isValidDataEntry(courier))
                    communicator.onSignUpDataConfirmed(courier);
                break;
            case R.id.profile_pic:
                    getImageFromDevice();
                break;
        
    

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) 
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==context.RESULT_OK)
            if(data!=null)
                if(requestCode==Constants.PROFILE_IMAGE_REQUEST_CODE) 
                    Uri imageUri = data.getData();
                    try 
                        Bitmap profileImage = MediaStore.Images.Media.getBitmap(context.getContentResolver(),imageUri);
                        this.userPhotoFile = new File(Utilities.getRealPathFromURI(imageUri,context));
                        profilePicImageView.setImageBitmap(Utilities.resizeBigImages(profileImage));
                     catch (IOException e) 
                        e.printStackTrace();
                    
                
            
        
    



    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) 
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) 
            case Constants.EXTERNAL_STORAGE_PERMISSIONS_REQUEST_CODE:
                if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) 
                    if (Build.VERSION.SDK_INT >= 23 && !shouldShowRequestPermissionRationale(Constants.STORAGE_PERMISSIONS[0])) 
                        Log.d(Constants.LOG_TAG, "noo");

                        Utilities.showBasicAlertDialog(
                                context,
                                R.drawable.ic_baseline_warning_24,
                                getString(R.string.permission_alert),
                                getString(R.string.go_to_settings_grant_the_storage_permissions_to_use_this_feature),
                                getString(R.string.ok),
                                null,
                                (dialog, which) -> 
                                    dialog.dismiss();
                                ,
                                null
                        );
                    
                    else
                        Utilities.showBasicAlertDialog(
                                context,
                                R.drawable.ic_baseline_warning_24,
                                getString(R.string.permission_alert),
                                getString(R.string.you_need_to_grant_storage_permissions),
                                getString(R.string.yes),
                                getString(R.string.not_now),
                                (dialog, which) -> 
                                    getImageFromDevice();
                                ,
                                (dialog, which) -> 
                                    dialog.dismiss();
                                
                        );
                    break;
                
        
    

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) 
        switch (buttonView.getId())
            case R.id.male_check_box:
                if(isChecked)
                    femaleCheckBox.setChecked(false);
                break;
            case R.id.female_check_box:
                if(isChecked)
                    maleCheckBox.setChecked(false);
                break;
            default:
                break;
        
    


```

【问题讨论】:

【参考方案1】:

我会尝试更改您拨打defineViews();setListeners(); 的位置

onCreateView() 是执行此操作的理想位置,因为它是 Fragment 本身使用的方法,而不是 Activity 生命周期使用的方法。

onActivityCreated() 仅在创建或重新附加片段时调用,但在重新启动时不调用。

【讨论】:

以上是关于关于片段生命周期的主要内容,如果未能解决你的问题,请参考以下文章

关于片段生命周期

关于Activity和Fragment生命周期的问题

理解片段事务期间片段的生命周期方法调用

调用 replace() 时片段的生命周期是啥?

在不存在的片段上调用片段生命周期和 onCreate 的问题

Android Jetpack -- Lifecycles篇