在Android Studio中使用imagebutton添加网络链接



我试图链接到我的应用程序内的网站。我使用碎片,所以我需要使用绑定。我已经设置了ImageButtons。我需要链接到网站的Java代码。我不太明白这些东西都到哪里去了

public class DashboardFragment extends Fragment {
private FragmentDashboardBinding binding;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
DashboardViewModel dashboardViewModel =
new ViewModelProvider(this).get(DashboardViewModel.class);
binding = FragmentDashboardBinding.inflate(inflater, container, false);
return binding.getRoot();
//*This section below gives me errors*
public void openWebPage(String url){
Uri facebook = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.facebook.com"));
if (intent.resolveActivity(getPackageManager()) !=null) {
startActivity(intent);
}
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
}

我需要打开多个不同的网站,使用不同的按钮为每个。

我不懂你的代码。如果你只是想用imagebutton打开一个web URL

试试这个

public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
binding =  FragmentMyBinding.inflate(inflater, container, false);
imageButton.setOnClickListener(view -> {
openWeb("https://stackoverflow.com/");
});
return binding.getRoot();
}
// Class to handle Urls
public void openWeb(String url){
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
}
catch (ActivityNotFoundException e){
Toast.makeText(this, "No app found for handle this Url", Toast.LENGTH_SHORT).show();
}
}

如果问题还没有解决,请告诉我。