如何从包含在另一个布局中的按钮单击中打开片段

How to open a fragment from a button click which is included in another layout

您好,我想通过单击按钮打开一个片段,但该按钮位于布局 snipet_profile.xml 中,并且我现在已将 snipet_profile.xml 包含在 fragment_profile 中,当我单击该按钮时它会发送打开我想打开的片段,我想在单击按钮时打开的片段是 EditProfile

好吧,如果您认为它有点令人困惑,请参阅我的代码

我试过一种方法,首先你必须找到有按钮的布局,在我的例子中是 RelativeLayout,所以我用这种方式实现

ProfleFragment.java

 RelativeLayout relativeLayout = view.findViewById(R.id.snipet_profile); // R.id.snipet_profile is the layout that i have included in Profile Fragment 

现在是按钮

Button editProfileButton;
editProfileButton = relativeLayout.findViewById(R.id.edit_profile_button); t// i have included relativelayout.findViewById so it can navigate or in simple this method i found 

错误 // 执行答案后

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myappnotfinal, PID: 12566
    android.view.InflateException: Binary XML file line #29 in com.example.myappnotfinal:layout/fragment_edit_profile: Binary XML file line #29 in com.example.myappnotfinal:layout/fragment_edit_profile: Error inflating class <unknown>
    Caused by: android.view.InflateException: Binary XML file line #29 in com.example.myappnotfinal:layout/fragment_edit_profile: Error inflating class <unknown>
    Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Constructor.newInstance0(Native Method)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
        at android.view.LayoutInflater.createView(LayoutInflater.java:858)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1010)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:965)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:1127)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1088)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:686)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:538)
        at com.example.myappnotfinal.Fragments.Profile.Edit_Profile.onCreateView(Edit_Profile.java:23)
        at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2963)
        at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:518)
        at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:282)
        at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2189)
        at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:2100)
        at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:2002)
        at androidx.fragment.app.FragmentManager.run(FragmentManager.java:524)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:224)
        at android.app.ActivityThread.main(ActivityThread.java:7562)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
     Caused by: java.lang.IllegalArgumentException: adjustViewBounds not supported.
        at de.hdodenhof.circleimageview.CircleImageView.setAdjustViewBounds(CircleImageView.java:141)
        at android.widget.ImageView.<init>(ImageView.java:215)
        at android.widget.ImageView.<init>(ImageView.java:188)
        at de.hdodenhof.circleimageview.CircleImageView.<init>(CircleImageView.java:98)
        at de.hdodenhof.circleimageview.CircleImageView.<init>(CircleImageView.java:94)
        at java.lang.reflect.Constructor.newInstance0(Native Method) 
        at java.lang.reflect.Constructor.newInstance(Constructor.java:343) 
        at android.view.LayoutInflater.createView(LayoutInflater.java:858) 
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1010) 
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:965) 
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:1127) 
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1088) 
        at android.view.LayoutInflater.inflate(LayoutInflater.java:686) 
        at android.view.LayoutInflater.inflate(LayoutInflater.java:538) 
        at com.example.myappnotfinal.Fragments.Profile.Edit_Profile.onCreateView(Edit_Profile.java:23) 
        at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2963) 
        at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:518) 
        at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:282) 
        at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2189) 
        at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:2100) 
        at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:2002) 
        at androidx.fragment.app.FragmentManager.run(FragmentManager.java:524) 
        at android.os.Handler.handleCallback(Handler.java:883) 
        at android.os.Handler.dispatchMessage(Handler.java:100) 
        at android.os.Looper.loop(Looper.java:224) 
        at android.app.ActivityThread.main(ActivityThread.java:7562) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950) 

现在是完整代码

Profile_Fragment.java

Button editProfileButton;
@SuppressLint("SourceLockedOrientationActivity")
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, 
    @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_profile, container, false);
        RelativeLayout relativeLayout = view.findViewById(R.id.snipet_profile);
        editProfileButton = relativeLayout.findViewById(R.id.edit_profile_button);
        editProfileButton.setOnClickListener(this::onClick);// added this line of code according to the answer

        return view;
    }
@Override
    public void onClick(View view) {
        Fragment fragment;
        if (view.getId() == R.id.edit_profile_button) {
            fragment = new Edit_Profile(); // Edit_Profile fragment
            replaceFragment(fragment);
        }
    }

    public void replaceFragment(Fragment fragment) {
        FragmentTransaction transaction = getParentFragmentManager().beginTransaction();
        transaction.replace(R.id.fragment_container, fragment);
        transaction.addToBackStack(String.valueOf(new Profile_Fragment()));
        transaction.commit();
    }

fragment_profile.xml

 <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:overScrollMode="never"
        android:paddingTop="20dp">

        <include
            android:id="@+id/snipet_profile"
            layout="@layout/snipet_profile" />

</LinearLayout>

snipet_profile.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true">
 <Button
        android:id="@+id/edit_profile_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/Followers"
        android:layout_centerHorizontal="true"
        android:layout_marginStart="5dp"
        android:layout_marginTop="20sp"
        android:backgroundTint="@color/dark_red"
        android:text="@string/edit_profile"
        android:textAllCaps="false"
        android:textColor="@color/white"
        android:textSize="15sp"
        android:textStyle="normal" />

</Button>

更新 1 // 添加了 EditProfile java 和 xml 文件

Edit_Profile.java // 这些是我试图在点击按钮时打开的片段

public class Edit_Profile extends Fragment {
    private CircleImageView profilePhoto;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_edit_profile, container, false);
        profilePhoto = view.findViewById(R.id.circleImageView);
        setProfileImage();
        initImageLoader();

        return view;
    }

    private void initImageLoader() {
        UniversalImageLoader universalImageLoader = new UniversalImageLoader(getContext());
        ImageLoader.getInstance().init(universalImageLoader.getConfig());
    }

    private void setProfileImage() {
        String imgUrl = "https://64.media.tumblr.com/1276b4edef49034af70bda14325385e3/d8872c747cafa206-96/s500x750/aa915fc49a84b5295f0cd44145d655b66eb906a6.jpg";
        UniversalImageLoader.setImage(imgUrl, profilePhoto, null, "");
    }
}

fragment_edit_profile.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/grey">

    <TextView
        android:id="@+id/done"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_marginTop="10dp"
        android:layout_marginEnd="10dp"
        android:elevation="10dp"
        android:text="@string/done"
        android:textColor="@color/white"
        android:textSize="15sp"
        android:textStyle="bold|normal" />

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/circleImageView"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:layout_below="@+id/done"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:adjustViewBounds="true"
        android:scaleType="centerCrop" />

    <TextView
        android:id="@+id/change_profilePhoto"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/circleImageView"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="5dp"
        android:text="@string/change_photo"
        android:textColor="@color/white"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/userName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/change_profilePhoto"
        android:layout_alignParentStart="true"
        android:layout_marginStart="20dp"
        android:layout_marginTop="15dp"
        android:text="@string/user_name"
        android:textColor="@color/white"
        android:textSize="16sp" />


    <EditText
        android:id="@+id/userNameEditText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/userName"
        android:layout_alignParentStart="true"
        android:layout_marginStart="20dp"
        android:layout_marginTop="5dp"
        android:autofillHints="User Name"
        android:background="@null"
        android:hint="@string/add"
        android:inputType="textNoSuggestions"
        android:textColor="@color/white"
        android:textColorHint="@color/lite_grey"
        android:textSize="16sp" />

    <TextView
        android:id="@+id/Name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/userNameEditText"
        android:layout_alignParentStart="true"
        android:layout_marginStart="20dp"
        android:layout_marginTop="20dp"
        android:text="@string/name"
        android:textColor="@color/white"
        android:textSize="16sp" />

    <EditText
        android:id="@+id/editTextTextFirstName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/Name"
        android:layout_alignParentStart="true"
        android:layout_marginStart="20dp"
        android:layout_marginTop="5dp"
        android:autofillHints="ADD"
        android:background="@null"
        android:hint="@string/add"
        android:inputType="textNoSuggestions"
        android:textColor="@color/white"
        android:textColorHint="@color/lite_grey"
        android:textSize="16sp" />

</RelativeLayout>

您必须为此 Button 设置 OnClickListener... 使用 editProfileButton.setOnClickListener(this); - this 用作您的 Fragment implements View.OnClickListener

编辑:好吧,你的堆栈跟踪说明了一切......

IllegalArgumentException: adjustViewBounds not supported.
    at de.hdodenhof.circleimageview.CircleImageView.setAdjustViewBounds(CircleImageView.java:141)

只需从 XML 声明的 CircleImageView 中删除 android:adjustViewBounds="true" 行。并删除 android:scaleType="centerCrop"。阅读 THIS 文章,其中您可以找到:

The ScaleType of CircleImageView is always CENTER_CROP and if we try to change it we get an exception. So it is perfect for the profile pictures.

Enabling adjustViewBounds is not supported as this requires an unsupported ScaleType