Placing event click on the button that is in a Fragment, in an Activity?

Asked

Viewed 2,358 times

3

I want to put a setOnClickListener on the button that is in a Fragment, through my Activity.

Follow the codes:

Activity:

private Button mButtonCriarConta;

//
onCreate da Activity...

mButtonCriarConta = (Button) findViewById(R.id.email_criar_button);
    Log.v("OnClick", "Nao Entrou no onClick");
    mButtonCriarConta.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Log.v("OnClick", "Entrou no onClick");
            Intent intent = new Intent(LoginActivity.this, DonoDoProntuarioActivity.class);

            Bundle parametros = new Bundle();
            String email = mEmailCriarNovo.getText().toString();
            String senhaCriar = mSenhaCriarNovo.getText().toString();
            parametros.putString("email", email);
            parametros.putString("senha", senhaCriar);

            intent.putExtras(parametros);
            startActivity(intent);
        }
    });

Fragment where the button is located

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    view = inflater.inflate(R.layout.fragment_criar_novo, container, false);

//resto do método
return view;}

XML of Fragment

<?xml version="1.0" encoding="utf-8"?>

<ScrollView
    android:id="@+id/login_form"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/email_novo_form"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/campoEmailNovoUsuario"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/prompt_email"
                android:inputType="textEmailAddress"
                android:maxLines="1"
                android:singleLine="true" />

        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/campoSenhaNovo"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/prompt_password"
                android:imeActionId="@+id/login"
                android:imeActionLabel="@string/action_sign_in_short"
                android:imeOptions="actionUnspecified"
                android:inputType="textPassword"
                android:maxLines="1"
                android:singleLine="true" />

        </android.support.design.widget.TextInputLayout>

        <CheckBox
            android:id="@+id/chk_mostrar_senha"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="@string/chk_mostrar_senha" />

        <!-- <FrameLayout
            android:id="@+id/fragment_placeholder"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"></FrameLayout>  -->
        <TextView
            android:id="@+id/texto_termos_criar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:textAlignment="center" />

        <Button
            android:id="@+id/email_criar_button"
            style="?android:textAppearanceSmall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="5dp"
            android:background="@drawable/botao_arredondado"
            android:gravity="center_horizontal|center_vertical"
            android:text="@string/acao_nova_conta"
            android:textColor="@color/branco"
            android:textStyle="bold" />

    </LinearLayout>
</ScrollView>

When I run the program on the phone of the app stopped working and only appears the log before entering setOnClickListener, what may be occurring and how to fix?

1 answer

4


You can’t/should do it like this. It’s the Fragment that should receive the events of its views.

The method findViewById() can only find the views that are part of the layout passed to the method setContentView().
As the button is not in layout of Activity, findViewById(R.id.email_criar_button); returns null.

The usual in these cases is to make the Fragment informed the Activity that the button was clicked.

For this, in the class of Fragment, define an interface that Actvity should be implemented in order to be notified:

public interface CreateEmailListener {
      public void onCreateEmail();
}  

Declare a private variable on Fragment to store the reference of Activity implementing the interface.

private CreateEmailListener mListener;  

At the event onAttach of Fragment obtain and retain the reference to Activity.

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mListener = (CreateEmailListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
        + " deve implementar CreateEmailListener");
    }
}  

It should now create the Onclicklistener to the button inside the method onCreateView of Fragment:

private Button mButtonCriarConta;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    view = inflater.inflate(R.layout.fragment_criar_novo, container, false);

    mButtonCriarConta = (Button) view.findViewById(R.id.email_criar_button);

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

            //Chame aqui o método da Activity
            mListener.onCreateEmail();
        }
    });

    //resto do método
    return view;
}

Now all we have to do is Activity implement the interface Createemaillistener and implement the method onCreateEmail()

If you want to pass some value on Fragment to the Activity state the method onCreateEmail() in order to accept parameters.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.