FaisalAhmed FaisalAhmed - 4 months ago 21
Android Question

ImageView onClick effect in fragment

Please correct me where i am wrong . I am trying to show some click effect on imageview click but it is throwing nullpointer exception . where i am wrong in this code ? It is throwing null pointer exception at createAllImage()

Fragment Code

public class DuaFragment extends Fragment implements View.OnTouchListener {

ImageView fear;

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.dua_fragment,container,false);
return view;
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
createAllImage();
}

@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
fear.getDrawable().setColorFilter(0x77000000, PorterDuff.Mode.SRC_ATOP);
fear.invalidate();
break;
case MotionEvent.ACTION_UP:
fear.getDrawable().clearColorFilter();
fear.invalidate();
break;
}
return true;
}

void createAllImage() {
fear=(ImageView)getView().findViewById(R.id.fear);
fear.setOnTouchListener(this);
}
}


My layout file

<ImageView
android:id="@+id/fear"
style="@style/icon"
android:background="@drawable/fear_96" />

Answer

As you mentioned, fear.getDrawable() is returning null.

So, we have two solutions.. Need to test:

Solution 1

fear.getDrawable() is null because you set the picture as android:background.

I created this fixed based in here and here

So, change your ImageView as follows:

<ImageView
    android:id="@+id/fear"
    style="@style/icon"
    android:src="@drawable/fear_96"
    android:scaleType="fitXY"       />

Solution 2

If you want to keep android:background in ImageView Layout file, try to get the drawable as follows:

fear.getBackgroundDrawable();