0

I managed to make a navigation drawer and trying to get a button working now.

Code:

public class FourthFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fourth_layout, container, false);
    }
    public void buttona1(View view){
        Intent browserIntent = new Intent(Intent.ACTION_VIEW,
                                          Uri.parse("https://www.google.nl"));
        startActivity(browserIntent);
    }
}

Layout:

<Button
    android:text="Magister"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="buttona1"
    android:id="@+id/button2"
    android:visibility="visible"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />

The problem is that when I open the app in my mobile and move to the button page, push the button the app will close and stop working.

Tanmay Patil
  • 6,723
  • 2
  • 22
  • 45

2 Answers2

0

You should initialize Context in your fragment contsructor which will be passed from your MainActivity while initializing freagment and call context.startActivity(YOUR_INTENT); hope this will help you

Kunal Dudka
  • 457
  • 1
  • 4
  • 14
0

your code seems correct but you need to make method buttona1 in your activity and fragment both . You can't call the method from xml resides in Fragment but not in Activity

you may use the following code inside the onCreateView method

    View v=inflater.inflate(R.layout.fourth_layout, container, false);
    Button myButton=(Button)v.findViewById(R.id.button2);
    myButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
    buttona1(view)
    });
return v;

also replace this line

 startActivity(browserIntent);

with

getActivity().startActivity(browserIntent);
Umar Ata
  • 2,820
  • 2
  • 19
  • 31