0

Im trying to add a link to my created button which is on a fragment. This is currently what I have. I can get the button working if it's on the main activity but I don't know what to do from there.

java

public class RideSharesFragment extends Fragment {

    public RideSharesFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_ride_shares, container, false);
    }

    public void Uber(View view){
        Intent browserIntent = new Intent(
            Intent.ACTION_VIEW, Uri.parse("https://m.uber.com/")
        );
        startActivity(browserIntent);
    }
}

XML

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/Ride_shares"
        android:textColor="@color/black"
        android:textSize="32sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_`enter code here`constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Lyft"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.203" />

    <Button
        android:id="@+id/Uber"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Uber"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button2" />

</androidx.constraintlayout.widget.ConstraintLayout>
hata
  • 11,633
  • 6
  • 46
  • 69

2 Answers2

0

startActivity(Intent) is a method of Context. So you can use it by preparing Context instance using requireContext() or getContext() in a Fragment and invoke the method on the instance:

 requireContext().startActivity(browserIntent);
hata
  • 11,633
  • 6
  • 46
  • 69
  • Now it just crashes the app. public void Uber(View view){ Intent browserIntent=new Intent(Intent.ACTION_VIEW, Uri.parse("https://m.uber.com/")); requireContext().startActivity(browserIntent); } – ChanCho Nov 03 '21 at 19:55
  • @ChanCho Please show your error log. – hata Nov 04 '21 at 03:05
0

From fragment you should use:

Java:

`getActivity().startActivity(browserIntent);`

Kotlin:

`activity?.startActivity(browserIntent)`

Using context in a fragment

edwell
  • 91
  • 1
  • 3