【发布时间】:2017-10-05 02:07:31
【问题描述】:
在尝试让我的所有 3 个按钮在片段中使用相同的点击事件后,public class FragmentShapesDemo extends android.support.v4.app.Fragment implements View.OnClickListener 变为红色下划线并返回错误:
类“FragmentShapesDemo”必须声明为抽象或在 OnClickListener 中实现抽象方法“onClick(View)”
我不明白为什么在实现点击事件时会出现此错误:-/
fragment_shapes_demo.xml
<Button
android:id="@+id/btn_1"
android:onClick="btn_Click"
android:text="@string/circles"/>
<Button
android:id="@+id/btn_2"
android:onClick="btn_Click"
android:text="@string/squares"/>
<Button
android:id="@+id/btn_3"
android:onClick="btn_Click"
android:text="@string/triangles"/>
FragmentShapesDemo.java
public class FragmentShapesDemo extends android.support.v4.app.Fragment {
Button button0;
Button button1;
Button button2;
public FragmentShapesDemo() {
// Required empty constructor
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_shapes_demo, container, false);
button0 = (Button) v.findViewById(R.id.btn_1);
button1 = (Button) v.findViewById(R.id.btn_2);
button2 = (Button) v.findViewById(R.id.btn_3);
button0.setOnClickListener(this);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
return v;
}
public void btn_Click(View v) {
Toast.makeText(getActivity(), "Hello World", Toast.LENGTH_LONG).show();
}
}
【问题讨论】:
-
为什么你在膨胀不同的视图时使用 getActivity().findViewById() 在你的情况下
标签: java android xml android-fragments android-button