我已经在相对布局中放置了一个坐标布局。协调器布局由两个按钮组成。我设计了通常的onclick功能,但是按钮似乎没有被点击。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="@+id/relativeLayoutMain"
android:layout_margin="0dp"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.example.shaby.payshare.WorkPageOneFragment">
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/add1"
android:layout_gravity="bottom|right"
android:text="ADDBene"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/add2"
android:layout_gravity="bottom|left"
android:text="AddItem"/>
</android.support.design.widget.CoordinatorLayout>
</RelativeLayout>
Java文件部件为
buttonAddB= (Button)view.findViewById(R.id.add1);
buttonAddB.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getContext(), "Hi", Toast.LENGTH_LONG).show();
}
});
问题是1)我做的是正确的事情吗? 2)如果是,那么为什么按钮不工作?帮助。
发布于 2017-03-08 18:46:41
有两个想法:
1)查看buttonAddB= (Button)view.findViewById(R.id.add1)
中的view
是什么,它指的是您认为它指的是什么;
2)你没有说当事情失败时会发生什么,所以我猜这是一个NPE。尝试将Toast.makeText(getContext(), "Hi", Toast.LENGTH_LONG).show()
更改为Toast.makeText(v.getContext(), "Hi", Toast.LENGTH_LONG).show()
,看看是否有效。getContext()
可能返回null。
如果这些都不能修复它,请发布更多关于失败的信息。
https://stackoverflow.com/questions/42673746
复制