0
votes

La déclaration de bouton dans le fragment entraîne la nullité d'Android

J'ai suivi différents liens et forums pour résoudre ce problème, mais je n'ai pas pu le résoudre. Donc je pense qu'il me manque quelque chose d'important dans mon code mais je ne comprends pas quoi.

La situation est la suivante. J'essaye d'appeler des écouteurs de clic à trois boutons. Quand je les ai initialisés (j'ai essayé dans onCreateView() et dans la méthode OnViewFragment() , également dans OnCreate() ) C'est dans un fragment. J'attache mon XML ci-dessous (une partie, bien sûr), j'ai essayé de l'invoquer en utilisant getActivity().findViewById(R.id.the_id_of_each_button) et aussi avec

package com.janus.janusapp;

import android.content.Context;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.Toast;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link profileFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class profileFragment 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";


    private Animation rotateOpen ;
    private Animation rotateClose ;
    private Animation fromBottom ;
    private Animation toBottom ;
    //Here is where I declare those three buttons
    private Button more_buttons;
    private Button edit_profile_picture;
    private Button edit_profile;
    private boolean clicked = false;

    /**====================================================================================================*/


    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;


    public profileFragment() {
        // Required empty public constructor
    }

    public static profileFragment newInstance(String param1, String param2) {
        profileFragment fragment = new profileFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);

        return fragment;
    }
   /*===================The OnCreateMethod===================================*/
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }


    }
    /*==================================================================================================
     * Here are some functions used by the buttons, but there's not where it fails, so, I just mention it.
    /*
    private void deployMoreButtons();
    private void setVisibility(boolean clicked);
    private void setAnimation(boolean clicked);
    private void setClickable(boolean clicked);

   /*=====================================The onCreateView() Method====================================*/
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_profile, container, false);


        rotateOpen = AnimationUtils.loadAnimation(getActivity(),R.anim.rotate_open_anim);
        rotateClose = AnimationUtils.loadAnimation( getActivity(),R.anim.rotate_close_anim);
        fromBottom = AnimationUtils.loadAnimation(getActivity(),R.anim.from_bottom_anim);
        toBottom = AnimationUtils.loadAnimation( getActivity(),R.anim.to_bottom_anim);
        /* I initialize my buttons right here, In the ways I tried before. When I use getActivity() it passes but the value of the burron seems to be null, and in the other way it just fails*/

        more_buttons =(Button) getActivity().findViewById(R.id.buttons_to_edit);
        edit_profile = (Button)getActivity().findViewById(R.id.edit_profile);
        edit_profile_picture =(Button) view.findViewById(R.id.edit_profile_picture);

        /* My button SetOnClickListeners, here is where my execution fails using getActivity()*/
        more_buttons.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deployMoreButtons();
            }
        });
        edit_profile_picture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Do Something
            }
        });

        edit_profile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Do Something
            }
        });
        return view;
    }

}

Je pense que c'est parce que j'ai mes boutons dans certaines mises en page, mais je n'ai pas trouvé comment résoudre ce problème.

Mon XML (maintenant):

<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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=".profileFragment">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/scrollableView">

        <ImageView
            android:id="@+id/profilePicture"
            android:layout_width="0dp"
            android:layout_height="225dp"
            android:background="@color/azulito"
            android:src="@drawable/default_prfile_picture"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/buttons_to_edit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginBottom="4dp"
            android:backgroundTint="#FFFFFF"
            android:focusable="true"
            android:tint="@color/azulito"
            android:src="@drawable/ic_baseline_add_24"
            app:backgroundTint="@color/azulito"
            app:borderWidth="0.5dp"
            app:layout_constraintBottom_toBottomOf="@id/profilePicture"
            app:layout_constraintEnd_toEndOf="@id/profilePicture" />


        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/edit_profile_picture"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:focusable="true"
            android:visibility="invisible"
            android:layout_marginBottom="64dp"
            android:backgroundTint="#FFFFFF"
            android:src="@drawable/ic_baseline_image_24"
            android:tint="@color/azulito"
            app:backgroundTint="@color/azulito"
            app:borderWidth="0.5dp"
            app:fabSize="mini"
            app:layout_constraintBottom_toTopOf="@id/buttons_to_edit"
            app:layout_constraintEnd_toEndOf="@+id/buttons_to_edit"
            app:layout_constraintStart_toStartOf="@+id/buttons_to_edit"
            app:rippleColor="@color/azulito" />

        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/edit_profile"
            android:visibility="invisible"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:layout_marginEnd="8dp"
            android:focusable="true"
            android:layout_marginBottom="4dp"
            android:backgroundTint="#FFFFFF"
            android:src="@drawable/ic_baseline_edit_24"
            app:backgroundTint="@color/azulito"
            app:borderWidth="0.5dp"
            app:fabSize="mini"
            app:layout_constraintBottom_toTopOf="@id/edit_profile_picture"
            app:layout_constraintEnd_toEndOf="@+id/edit_profile_picture"
            app:layout_constraintStart_toStartOf="@+id/edit_profile_picture" />


      <!-- here is more XML code, but nothing really relevant for this purposes-->


    </androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>

Et mon code Java (pour ce fragment particulier car d'autres fonctionnent bien):

View view = inflater.inflate(R.layout.fragment_profile, container, false);
one_of_my_buttons =(Button) getActivity().findViewById(R.id.the_id_of_one_of_my_buttons);

Alors qu'est-ce que je fais mal et que puis-je faire? Merci de votre aide.


1 commentaires

le bouton avec l'ID the_id_of_one_of_my_buttons est-il défini dans l'activité xml ou le fragment xml?


5 Réponses :


0
votes

vous utilisez Fragment et vous gonflez déjà. Donc

more_buttons =(Button) view.findViewById(R.id.buttons_to_edit);
        edit_profile = (Button) view.findViewById(R.id.edit_profile);
        edit_profile_picture =(Button) view.findViewById(R.id.edit_profile_picture);

à

more_buttons =(Button) getActivity().findViewById(R.id.buttons_to_edit);
        edit_profile = (Button)getActivity().findViewById(R.id.edit_profile);
        edit_profile_picture =(Button) view.findViewById(R.id.edit_profile_picture);


1 commentaires

Ça a marché. Merci: 3



0
votes

Vous utilisez une référence d' activité pour trouver l'ID des boutons, mais le bouton est dans votre fragment xml que vous avez gonflé et vous pouvez ensuite trouver les identifiants des boutons définis dans fragment xml en utilisant la vue comme indiqué ci-dessous

View view = inflater.inflate(R.layout.fragment_profile, container, false);
one_of_my_buttons =(Button) view.findViewById(R.id.the_id_of_one_of_my_buttons);


0 commentaires

0
votes

En utilisation onCreateView

view.findViewById(YourId);


1 commentaires

Ça marche. Merci: 3



2
votes

Comme vous avez déclaré la mise en page gonflée pour le fragment comme "vue", maintenant si vous voulez appeler quelque chose de la vue, vous devez l'utiliser comme ...

view.edit_profile

Ici, lorsque vous tapez view. Cela signifie que vous appelez la vue à partir de la mise en page que vous avez gonflée en tant que vue.


1 commentaires

Ça a marché. Merci: 3



0
votes

Ok, maintenant peut-être que je vais gagner un peu de haine ...

La classe des boutons que j'avais sont FloatingActionButton c'est pourquoi ils ne fonctionnaient pas avec view inflater. Maintenant ça marche bien. J'ai utilisé les solutions que tout le monde a prises ici. Merci.


0 commentaires