【发布时间】:2020-07-10 19:14:06
【问题描述】:
我对 Android Studio 很陌生。我想要的很简单:我按下一个按钮,应该会发生一些事情。
所以我的片段中有一个按钮,在 XML 中看起来像这样:
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="60dp"
android:gravity="center_vertical"
android:text="@string/hello"
android:onClick="doSumth"
/>
我在 GeneralFragment.java 中的代码如下所示:
package ch.yourclick.kitt.fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import ch.yourclick.kitt.R;
/**
* A simple {@link Fragment} subclass.
* Use the {@link GeneralFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class GeneralFragment extends Fragment {
public GeneralFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @return A new instance of fragment General.
*/
// TODO: Rename and change types and number of parameters
public static GeneralFragment newInstance() {
GeneralFragment fragment = new GeneralFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_general, container, false);
}
public void doSumth() {
System.out.println("Hello");
}
}
我的问题是我得到了错误:
java.lang.IllegalStateException: 在视图类 androidx.appcompat.widget.App 上定义的 android:onClick 属性的父或祖先上下文中找不到方法 doSumth(View)
我做错了什么?
【问题讨论】:
标签: java android android-fragments