I'm trying to make a method that acts as a ColorStateList
or Selector when a View is pressed. When a view is passed into the method onClickColorSelector
it takes the view and sets a setOnTouchListener
, so when the user press down on a view
, the view gets a selector effect.
Now the problem is that onTouchListener
is only called when a View is clicked for the second time. Why does it behave like that and how to solve it?
Note! Dont suggest me ColorStateList!
onClickColorSelector is in a class called ViewSelector
public void onClickColorSelector(View view, final int onPressColor) {
Log.d("TAG" , "1");
view.setOnTouchListener(new View.OnTouchListener() {
int defaultTextColor = 0;
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
Log.d("TAG" , "2");
if (view instanceof TextView) {
Log.d("TAG" , "3");
defaultTextColor = ((TextView) view).getCurrentTextColor();
((TextView) view).setTextColor(onPressColor);
}
Log.d("TAG" , "4");
view.getBackground().setColorFilter(Color.RED, PorterDuff.Mode.SRC_ATOP);
return true;
} else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
if (view instanceof TextView) {
((TextView) view).setTextColor(defaultTextColor);
}
view.getBackground().setColorFilter(null);
return true;
}
return false;
}
});
}
This is how onClickColorSelector();
is called from a another class:
ViewSelector vs = new ViewSelector(this);
loginBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
vs.onClickColorSelector(loginBtn, Color.RED);
}
});
It's Activated on when you press the button ...
That is the reason it running 2nd time ....
So call this
vs.onClickColorSelector(loginBtn, Color.RED);
in yourOnCreate()
method
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.