每当我将ImageView设置为可点击时,它就会崩溃。是不是可以在按钮内部使用可点击的ImageView,或者只是做错了?我已将图像设置为可点击。
** 已编辑 **
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
btPlumbers.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(HomeActivity.this);
View layoutPlumber = getLayoutInflater().inflate(R.layout.layout_plumber, null);
bottomSheetDialog.setContentView(layoutPlumber);
BottomSheetBehavior bottomSheetBehavior = BottomSheetBehavior.from((View) layoutPlumber.getParent());
bottomSheetBehavior.setPeekHeight(
(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 400, getResources().getDisplayMetrics())
);
ImageView imgPTap = (ImageView) findViewById(R.id.imageview_pTap);
imgPTap.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//
}
});
bottomSheetDialog.show();
}
});
以下是错误:
E/UncaughtException: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.fixitph.client.HomeActivity$1.onClick(HomeActivity.java:189)
at android.view.View.performClick(View.java:4781)
at android.view.View$PerformClick.run(View.java:19900)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:159)
at android.app.ActivityThread.main(ActivityThread.java:5541)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:975)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:770)
XML文件
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/imageview_pTap"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="0"
android:layout_gravity="center"
android:layout_row="0"
android:clickable="true"
android:padding="15dp"
app:srcCompat="@drawable/ic_plumber_64dp" />
</android.support.constraint.ConstraintLayout>
使用XML编辑
答案 0 :(得分:2)
btPlumbers 或 imgPtap 为空。尝试在调用setOnClickListener()
你可以这样做:
btPlumbers = findViewById(R.id.<your_view_id>);
imgPtap = findViewById(R.id.<your_view_id>);
答案 1 :(得分:1)
而不是
ImageView imgPTap = (ImageView) findViewById(R.id.imageview_pTap);
在您的活动中尝试此操作。
ImageView imgPTap = (ImageView) layoutPlumber.findViewById(R.id.imageview_pTap);
(仍然将此问题标记为重复)