【问题标题】:Fragment button with a link to a website doesn't work带有网站链接的片段按钮不起作用
【发布时间】:2021-12-17 10:41:17
【问题描述】:

我正在尝试将链接添加到我在片段上创建的按钮。这是我目前所拥有的。如果它在主要活动上,我可以让按钮工作,但我不知道从那里做什么。

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>

【问题讨论】:

    标签: android android-fragments


    【解决方案1】:

    startActivity(Intent)Context 的一个方法。因此,您可以通过在 Fragment 中使用 requireContext()getContext() 准备 Context 实例并调用实例上的方法来使用它:

     requireContext().startActivity(browserIntent);
    

    【讨论】:

    • 现在它只是让应用程序崩溃。 public void Uber(View view){ Intent browserIntent=new Intent(Intent.ACTION_VIEW, Uri.parse("m.uber.com/")); requireContext().startActivity(browserIntent); }
    • @ChanCho 请显示您的错误日志。
    猜你喜欢
    • 2019-04-23
    • 2023-03-28
    • 1970-01-01
    • 2014-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多