Search code examples
androidandroid-intentandroid-fragmentsandroid-actionbarandroid-tabs

Intend inside fragment class


In my activity using tab for action bar, but what I try to do is when I'm in one of the options my tab, have a button in that fragment and click go to another activity, but I have an error on my Intent on which tells me that is not defined.

Someone can help me?

Thank you very much.

package com.example.dona1click;

import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;


public class Nosotros extends Fragment {
    Button Btn;
    Intent intent;


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

        View x = inflater.inflate(R.layout.nosotros, container, false);

        Btn = (Button)x.findViewById(R.id.button1);

        Btn.setOnClickListener(new OnClickListener() { // evento clic del boton

            @Override
            public void onClick(View v) {

                // al hacer clic se manda para la otra pagina


                intent = new Intent (this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);             
                startActivity(intent);

                //---------------------------------------------


            }

        }); 

        return x;
    }
}

Solution

  • The first parameter in the Intent constructor must be a Context and Fragment does not extend Context. Use intent = new Intent(getActivity(), MainActivity.class); instead, as Activity does extend Context.