Android Studio - 片段 onClickListener 不起作用 [英] Android Studio - Fragment onClickListener not working
问题描述
在查看所有可能的答案后,我找不到我的代码有什么问题.
After reviewing every possible answer, I cannot find what's wrong with my code.
我需要在 3 个片段上有一个 OnClickListener,其中一个由 mainActivity 加载.他们都没有工作.我已经在每个片段上实现了 OnClickListener.
I need to have an OnClickListener on 3 fragments, one of them being loaded by the mainActivity. None of them are working. I have implemented the OnClickListener on each fragment.
这是我的代码:
RequestFragment1.java
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_request1, container, false);
Button buttonRequest1 = (Button) view.findViewById(R.id.Request1Button);
buttonRequest1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String url = "https://www.google.ca/";
WebView httpRequestResult = (WebView) getActivity().findViewById(R.id.webViewResult);
httpRequestResult.getSettings().setJavaScriptEnabled(false);
httpRequestResult.loadUrl(url);
getActivity().setContentView(R.layout.requests_webview);
}
});
return view;
}
fragment_request1.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="@+id/Request1Button"
android:layout_width="match_parent"
android:layout_height="90dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:text="Requête 1" />
</RelativeLayout>
MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_request1);
View currentView = findViewById(android.R.id.content);
//Implementation du TouchListener
currentView.setOnTouchListener(new SwipeListener(MainActivity.this) {
它需要通过按下 Request1Button 来打开一个 webview.
It needs to open a webview by pressing Request1Button.
感谢您的宝贵时间!
推荐答案
setContentView(R.layout.fragment_request1);
MainActivity.onCreate()
中的这一行扩展了名为 fragment_request1
的 XML 文件中定义的布局.但是,它不会创建一个片段.因此,永远不会调用 RequestFragment1.onCreateView()
并且永远不会设置 OnClickListener
.
This line in MainActivity.onCreate()
inflates the layout defined in the XML file named fragment_request1
. However, it does not create a fragment. Therefore, RequestFragment1.onCreateView()
is never called and the OnClickListener
is never set.
您需要正确创建片段并使用 FragmentManager
加载它.有许多在线教程展示了如何执行此操作.我建议从 Android 开发者网站上的那个开始.
You need to properly create the fragment and load it with FragmentManager
. There are many online tutorials that show how to do this. I suggest starting with the one on the Android Developer website.
这篇关于Android Studio - 片段 onClickListener 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!