安卓如何通过单击片段xml文件上的按钮从片段java文件打开新活动?
我需要通过单击片段xml文件上的按钮来打开一个新活动
我在片段java文件中编写了一些代码,通过单击片段xml文件上的按钮来调用新活动
当我运行应用程序时,它崩溃了
我得到的错误在第行的片段java文件中
“公共真空电子(视图)”
08-02 10:58:55.654 3519-3519/com.example.mohammadzakriya.tabhost E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mohammadzakriya.tabhost, PID: 3519
java.lang.IllegalStateException: Could not find method electronics(View) in a parent or ancestor Context for 安卓:onClick attribute defined on view class 安卓.support.v7.widget.AppCompatButton with id 'button2'
at 安卓.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:327)
at 安卓.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
at 安卓.view.View.performClick(View.java:5198)
at 安卓.view.View$PerformClick.run(View.java:21147)
at 安卓.os.Handler.handleCallback(Handler.java:739)
at 安卓.os.Handler.dispatchMessage(Handler.java:95)
at 安卓.os.Looper.loop(Looper.java:148)
at 安卓.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.安卓.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.安卓.internal.os.ZygoteInit.main(ZygoteInit.java:616)
XML
<LinearLayout
xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
xmlns:tools="http://schemas.安卓.com/tools"
安卓:layout_width="match_parent"
安卓:layout_height="match_parent"
安卓:orientation="vertical"
tools:context=".FolderScale">
<TextView
安卓:id="@+id/textView4"
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content"
安卓:layout_gravity="center"
安卓:text="1"
安卓:textAlignment="center" />
<Button
安卓:id="@+id/button2"
安卓:layout_width="match_parent"
安卓:layout_height="wrap_content"
安卓:layout_gravity="center_horizontal"
安卓:text="Electronics"
安卓:onClick="electronics"/>
</LinearLayout>
Java
public class TopfreeFragment extends Fragment {
public TopfreeFragment() {
// 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_topfree, container, false);
}
public void electronics(View view) {
Intent intent = new Intent(getActivity(),Electronicspage.class);
startActivity(intent);
}
}
# 1 楼答案
最后,根据我的代码,通过一些eidt得到了答案的解决方案
感谢@vrund purohit提供链接How to handle button clicks using the XML onClick within Fragments
它帮助我最终理解了下面的代码