TextView OnClickListener не работает во фрагментах - PullRequest
0 голосов
/ 05 сентября 2018

Итак, моя проблема, скажем, мы находимся в SignInFragment (Для навигации в SignInFragment, пусковая установка - это MainActivity внутри, которая откроет HomeFragment, тогда внутри HomeFragment есть код, если есть если пользователь не вошел в систему, он перейдет к SignInFragment), затем в SignInFragment появится TextView «У вас еще нет учетной записи? Зарегистрируйтесь здесь». Поэтому, когда я нажимаю, ничего не происходит. Надеюсь, вы понимаете.

Я добавлю другие фрагменты, чтобы легко понять поток моего приложения.

Вот коды для: MainActivity

import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends FragmentActivity {

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


    HomeActivity fragment = new HomeActivity();

    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.replace(R.id.container, fragment, fragment.getTag());
    ft.commit();

}

Вот коды для: HomeActivity

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class HomeActivity extends Fragment {

private static final String TAG = "HomeActivity";

TextView mWelcome;
Button btnSignout;

//Firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.home_activity, container, false);

    mWelcome = view.findViewById(R.id.welcome);
    btnSignout = view.findViewById(R.id.btnSignOut);

    setupFirebaseAuth();

    //Firebase
    mAuth = FirebaseAuth.getInstance();

    btnSignout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            FragmentTransaction ft = getFragmentManager().beginTransaction();
            ft.replace(R.id.container, new SignOutFragment());
            ft.commit();
        }
    });

    return view;
}

/*
-------------------------------Firebase--------------------------------
 */

/*
check if the user is logged in
 */
private void checkCurrentUser(FirebaseUser user){
    Log.d(TAG, "checkCurrentUser: checking if user is logged in.");

    if (user == null){

        SignInFragment fragment = new SignInFragment();
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.remove(HomeActivity.this);
        ft.replace(R.id.container, fragment);
        ft.commit();

    }
}

private void setupFirebaseAuth(){
    Log.d(TAG, "setupFirebaseAuth: setting up firebase auth.");

    mAuth = FirebaseAuth.getInstance();

    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            //checking if the user is logged in or not remove
           // checkCurrentUser(user);

            if (user != null){
                //User is signed in
                Log.d(TAG, "onAuthStateChanged: signed_in: " + user.getUid());

            }else {
                // User is signed out
                Log.d(TAG, "onAuthStateChanged: signed_out");



            }
        }
    };

}

@Override
public void onStart() {
    super.onStart();
    mAuth.addAuthStateListener(mAuthListener);
    checkCurrentUser(mAuth.getCurrentUser());
}

@Override
public void onStop() {
    super.onStop();

    if (mAuthListener != null){
        mAuth.removeAuthStateListener(mAuthListener);
    }
}

Вот коды для: SignInFragment

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class SignInFragment extends Fragment {

private static final String TAG = "SignInFragment";

private TextView mEmail, mPassword, mHeading, mToRegister, mFckyou;
private EditText eEmail, ePassword;
private Button btnSignin;
private ProgressBar mProgressBar;

//Firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.signin_fragment, container, false);

    //TextView
    mEmail = view.findViewById(R.id.tvEmail);
    mPassword = view.findViewById(R.id.tvPassword);
    mHeading = view.findViewById(R.id.heading);
    mToRegister = view.findViewById(R.id.tvToRegister);
    mFckyou = view.findViewById(R.id.fckyou);
    //EditText
    mEmail = view.findViewById(R.id.etEmail);
    ePassword = view.findViewById(R.id.etPassword);
    //Button
    btnSignin = view.findViewById(R.id.btnSignin);
    //ProgressBar
    mProgressBar = view.findViewById(R.id.progressBar);

    //Progress Bar and Text view = GONE
    mProgressBar.setVisibility(View.GONE);
    mFckyou.setVisibility(View.GONE);

    navigateToReigster();
    setupFirebaseAuth();
    signInUser();

    return view;
}

public void navigateToReigster(){

    mToRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            RegisterFragment fragment = new RegisterFragment();

            FragmentTransaction ft = getFragmentManager().beginTransaction();
            ft.replace(R.id.container, fragment, fragment.getTag());
            ft.commit();
        }
    });
}

private boolean isStringNull(String string){

    if (string.equals("")){
        return true;
    }

    return false;
}

    /*
---------------------------------Firebase-----------------------------------
 */


private void signInUser(){
    // Button = to sign in the user.
    btnSignin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String email = eEmail.getText().toString();
            String password = ePassword.getText().toString();

            if (isStringNull(email) && isStringNull(password)){

                Toast.makeText(getActivity(), "You must field out all the fields.", Toast.LENGTH_SHORT).show();
            }else {

                //Progress Bar and TextView be visible
                mProgressBar.setVisibility(View.VISIBLE);
                mFckyou.setVisibility(View.VISIBLE);

                //To sign in users
                mAuth.signInWithEmailAndPassword(email, password)
                        .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                            @Override
                            public void onComplete(@NonNull Task<AuthResult> task) {

                                if (task.isSuccessful()){
                                    Toast.makeText(getActivity(), "Sign in Successful!", Toast.LENGTH_SHORT).show();

                                    FragmentTransaction ft = getFragmentManager().beginTransaction();
                                    ft.replace(R.id.container, new HomeActivity());
                                    ft.commit();


                                }else {
                                    //Progress bar and Text View will be GONE. So the users can try again.
                                    mProgressBar.setVisibility(View.GONE);
                                    mFckyou.setVisibility(View.GONE);
                                    Toast.makeText(getActivity(), "Could not sign in. Please try again.", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
            }

        }
    });


}

Вот мои коды для: RegisterFragment

 import android.os.Bundle;
 import android.support.annotation.NonNull;
 import android.support.annotation.Nullable;
 import android.support.v4.app.Fragment;
 import android.support.v4.app.FragmentTransaction;
 import android.util.Log;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.Button;
 import android.widget.EditText;
 import android.widget.ProgressBar;
 import android.widget.TextView;
 import android.widget.Toast;

 import com.google.android.gms.tasks.OnCompleteListener;
 import com.google.android.gms.tasks.Task;
 import com.google.firebase.auth.AuthResult;
 import com.google.firebase.auth.FirebaseAuth;
 import com.google.firebase.auth.FirebaseUser;

 public class RegisterFragment extends Fragment {

private static final String TAG = "RegisterFragment";

private TextView mEmail, mPassword, mHeading, mToSignin, mFckyou;
private EditText eEmail, ePassword;
private Button btnRegister;
private ProgressBar mProgressBar;

//Firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private String userID;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.register_fragment, container, false);

    //TextView
    mEmail = view.findViewById(R.id.tvEmail);
    mPassword = view.findViewById(R.id.tvPassword);
    mHeading = view.findViewById(R.id.heading);
    mToSignin = view.findViewById(R.id.tvToSignin);
    mFckyou = view.findViewById(R.id.fckyou);
    //EditText
    mEmail = view.findViewById(R.id.etEmail);
    ePassword = view.findViewById(R.id.etPassword);
    //Button
    btnRegister = view.findViewById(R.id.btnRegister);
    //ProgressBar
    mProgressBar = view.findViewById(R.id.progressBar);

    //Progress Bar and Text View = GONE
    mProgressBar.setVisibility(View.GONE);
    mFckyou.setVisibility(View.GONE);

    navigateToSignIn();
    registerNewUser();
    setupFirebaseAuth();

    return view;
}

public void navigateToSignIn(){

    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(R.id.container, new SignInFragment());
    ft.commit();
}

private boolean isStringNull(String string){

    if (string.equals("")){
        return true;
    }

    return false;
}

/*
To check if the user is creating a same email.
 */
public void checkUserId(){

    if (mAuth.getCurrentUser() != null){
        userID = mAuth.getCurrentUser().getUid();
    }
}

/*
---------------------------------Firebase-----------------------------------
 */



public void registerNewUser(){
    // To register new user
    btnRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String email = eEmail.getText().toString();
            String password = ePassword.getText().toString();

            if (isStringNull(email) && isStringNull(password)){

                Toast.makeText(getContext(), "You must field out all the fields.", Toast.LENGTH_SHORT).show();
            }else {

                //Progress Bar and TextView be visible
                mProgressBar.setVisibility(View.VISIBLE);
                mFckyou.setVisibility(View.VISIBLE);

                //To create/register new user
                mAuth.createUserWithEmailAndPassword(email, password)
                        .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                            @Override
                            public void onComplete(@NonNull Task<AuthResult> task) {

                                if (task.isSuccessful()){
                                    //user is succesfully registered and logged in
                                    checkUserId(); //Checking if the user is create same email
                                    Log.d(TAG, "onComplete: AuthstateChange: " + userID);
                                    Toast.makeText(getActivity(), "Registered Successfully", Toast.LENGTH_SHORT).show();

                                    //AFter Registering account it will navigate to the Login Fragment
                                    FragmentTransaction fr = getFragmentManager().beginTransaction();
                                    fr.replace(R.id.container, new SignInFragment());
                                    fr.commit();


                                }else {
                                    //If can't register the Progresss bar and Text view will be gone, so users can sign in again.
                                    //Progress Bar and Text View = GONE. So users can try again.
                                    mProgressBar.setVisibility(View.GONE);
                                    mFckyou.setVisibility(View.GONE);
                                    Toast.makeText(getActivity(), "Please check your internet. Or maybe you registered same email.", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });


            }

        }
    });


}

Вот мои коды для: register_fragment.xml

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/heading"
    android:text="Register"
    android:textColor="#000"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="20dp"
    android:textSize="50sp"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/tvEmail"
    android:text="Email"
    android:layout_below="@+id/heading"
    android:layout_marginLeft="10dp"
    android:layout_marginTop="100dp"/>
<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/etEmail"
    android:textColor="#000"
    android:hint="Type your email here..."
    android:layout_below="@+id/tvEmail"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/tvPassword"
    android:text="Password"
    android:layout_below="@+id/etEmail"
    android:layout_marginTop="20dp"
    android:layout_marginLeft="10dp"/>

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/etPassword"
    android:inputType="textPassword"
    android:layout_below="@+id/tvPassword"
    android:hint="Type your password here..."
    />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/btnRegister"
    android:text="Register"
    android:layout_below="@+id/etPassword"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="10dp"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/tvToSignin"
    android:text="Already have an account? Sign in here."
    android:textColor="@color/colorPrimary"
    android:textSize="10sp"
    android:layout_below="@+id/btnRegister"
    android:layout_marginTop="10dp"
    android:layout_centerHorizontal="true"/>

<ProgressBar
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/progressBar"
    android:layout_below="@+id/tvEmail"
    android:layout_marginTop="35dp"
    android:layout_centerHorizontal="true"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/fckyou"
    android:text="That's bad"
    android:textColor="@color/colorAccent"
    android:textStyle="bold"
    android:layout_below="@+id/progressBar"
    android:layout_centerHorizontal="true"/>

Вот мои коды для: signin_fragment.xml

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/heading"
    android:text="Sign In"
    android:textColor="#000"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="20dp"
    android:textSize="50sp"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/tvEmail"
    android:text="Email"
    android:layout_below="@+id/heading"
    android:layout_marginLeft="10dp"
    android:layout_marginTop="100dp"/>
<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/etEmail"
    android:textColor="#000"
    android:hint="Type your email here..."
    android:layout_below="@+id/tvEmail"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/tvPassword"
    android:text="Password"
    android:layout_below="@+id/etEmail"
    android:layout_marginTop="20dp"
    android:layout_marginLeft="10dp"/>

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/etPassword"
    android:inputType="textPassword"
    android:layout_below="@+id/tvPassword"
    android:hint="Type your password here..."
    />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/btnSignin"
    android:text="Sign in"
    android:layout_below="@+id/etPassword"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="10dp"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/tvToRegister"
    android:text="Do not have a account yet? Register here."
    android:textColor="@color/colorPrimary"
    android:textSize="10sp"
    android:layout_below="@+id/btnSignin"
    android:layout_marginTop="10dp"
    android:layout_centerHorizontal="true"/>

<ProgressBar
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/progressBar"
    android:layout_below="@+id/tvEmail"
    android:layout_marginTop="35dp"
    android:layout_centerHorizontal="true"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/fckyou"
    android:text="Fuck you..."
    android:textColor="@color/colorAccent"
    android:textStyle="bold"
    android:layout_below="@+id/progressBar"
    android:layout_centerHorizontal="true"/>

Ответы [ 3 ]

0 голосов
/ 05 сентября 2018

Я думаю, что проблема с getFragmentManager(), при использовании фрагментов из v4.app.Fragment необходимо использовать getSupportFragmentManager()

Обновление:

Я только что понял, что вы начинаете новый фрагмент с фрагмента. Хотя это не очень хорошая практика, и вы всегда должны позволять своей родительской деятельности совершать фрагментные транзакции. Вы можете узнать больше здесь и здесь

Но сейчас вы можете получить ссылку на getSupportFragmentManager(), например:

mToRegister.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        RegisterFragment fragment = new RegisterFragment();
        FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.container, fragment, fragment.getTag());
        ft.commit();
    }
});
0 голосов
/ 05 сентября 2018

Вы установили свой TextView для кликабельного

0 голосов
/ 05 сентября 2018
    //Home Activity 
    //implemet View.OnClickListener  , it is working

  import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class SignInFragment extends Fragment implements View.OnClickListener {

private static final String TAG = "SignInFragment";

private TextView mEmail, mPassword, mHeading, mToRegister, mFckyou;
private EditText eEmail, ePassword;
private Button btnSignin;
private ProgressBar mProgressBar;

//Firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.signin_fragment, container, false);

    //TextView
    mEmail = view.findViewById(R.id.tvEmail);
    mPassword = view.findViewById(R.id.tvPassword);
    mHeading = view.findViewById(R.id.heading);
    mToRegister = view.findViewById(R.id.tvToRegister);
    mFckyou = view.findViewById(R.id.fckyou);
    //EditText
    mEmail = view.findViewById(R.id.etEmail);
    ePassword = view.findViewById(R.id.etPassword);
    //Button
    btnSignin = view.findViewById(R.id.btnSignin);
    //ProgressBar
    mProgressBar = view.findViewById(R.id.progressBar);

    //Progress Bar and Text view = GONE
    mProgressBar.setVisibility(View.GONE);
    mFckyou.setVisibility(View.GONE);
    mToRegister.setOnClickListener(this);

    setupFirebaseAuth();
    signInUser();

    return view;
}

public void navigateToReigster(){

   Fragment fragment = new RegisterFragment();
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.container, fragment).commit();



    });

}
  @Override
    public void onClick(View vv) {
        if (vv == mToRegister) {
         navigateToReigster();
        }
        }

private boolean isStringNull(String string){

    if (string.equals("")){
        return true;
    }

    return false;
}

    /*
---------------------------------Firebase-----------------------------------
 */


private void signInUser(){
    // Button = to sign in the user.
    btnSignin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String email = eEmail.getText().toString();
            String password = ePassword.getText().toString();

            if (isStringNull(email) && isStringNull(password)){

                Toast.makeText(getActivity(), "You must field out all the fields.", Toast.LENGTH_SHORT).show();
            }else {

                //Progress Bar and TextView be visible
                mProgressBar.setVisibility(View.VISIBLE);
                mFckyou.setVisibility(View.VISIBLE);

                //To sign in users
                mAuth.signInWithEmailAndPassword(email, password)
                        .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                            @Override
                            public void onComplete(@NonNull Task<AuthResult> task) {

                                if (task.isSuccessful()){
                                    Toast.makeText(getActivity(), "Sign in Successful!", Toast.LENGTH_SHORT).show();

                                    FragmentTransaction ft = getFragmentManager().beginTransaction();
                                    ft.replace(R.id.container, new HomeActivity());
                                    ft.commit();


                                }else {
                                    //Progress bar and Text View will be GONE. So the users can try again.
                                    mProgressBar.setVisibility(View.GONE);
                                    mFckyou.setVisibility(View.GONE);
                                    Toast.makeText(getActivity(), "Could not sign in. Please try again.", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
            }

        }
    });


}
...