Reputation: 3651
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" />
Upvotes: 0
Views: 560
Reputation: 18687
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();
Upvotes: 1