Calling an Activity within a Fragment - Android Studio

Asked

Viewed 1,746 times

1

I need from the click of a button inside my Fragment, it call an Activity. My code is like this:

public class ActFoto2 extends Fragment implements View.OnClickListener, 
ViewTreeObserver.OnGlobalLayoutListener {

    private Button proximo;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);

        String caminhoFoto = Util.getUltimaMidia(getActivity(), Util.MIDIA_FOTO);

        if (caminhoFoto != null) {
            mCaminhoFoto = new File(caminhoFoto);
        }

        proximo = (Button)getActivity().findViewById(R.id.btnProximo);

        proximo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), ActMapa.class);
                startActivity(intent);
            }
        });
    }
} 

But still it does not call, and when I go to test, it for the application. Can someone please assist me. Thanks.

  • 1

    Welcome to Sopt. Add the full stack of errors to the question. this makes it easy to help!

  • You added the screen in your AndroidManifest.xml?

  • If proximo is a button of Activity declare the setOnClickListener() there, if it is not the code is wrong. Post the log of errors.

2 answers

0


public class ActFoto2 extends Fragment implements View.OnClickListener, ViewTreeObserver.OnGlobalLayoutListener {

private Button proximo;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
    // Define o XML do seu Fragment (o que contem o Button)
    return inflater.inflate(R.layout.meulayout, parent, false);
}

// Qualquer alteração com o Layout XML e Java API deve ser feito aqui ex: Clicks etc.
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {

    proximo = (Button)view.findViewById(R.id.btnProximo);

    proximo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), ActMapa.class);
            startActivity(intent);
        }
    });

}}

That solves.

  • Perfect. Thank you very much Alessandro, it worked.

  • I’m glad it worked, mark now as the right answer

-1

Try it like this:

   Intent intent = new Intent(getActivity(), ActMapa.class);
   getActivity().startActivity(intent);

Browser other questions tagged

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