java-选择时如何更改卡片视图的颜色
作者:互联网
我正在尝试卡片视图而不是按钮视图,我喜欢可以添加到他们的信息量.但是我想这样做,所以如果他们按卡片,它就会变色.一旦发布,我希望它变回来.因此它的工作方式与我的按钮类似.
我可以得到它,以便它在单击时发生变化,但是直到活动被破坏之前,它都保持不变,
这是我目前用于更改颜色的代码.
public void setSingleEvent(GridLayout maingrid) {
for (int i = 0; i < maingrid.getChildCount(); i++) {
final CardView cardView = (CardView) maingrid.getChildAt(i);
final int finalI = i;
cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(mcontext, "Button: " + finalI, Toast.LENGTH_SHORT).show();
cardView.setCardBackgroundColor(mcontext.getResources().getColor(R.color.buttonPressed));
if (finalI == 0) {
mcontext.startActivity(new Intent(mcontext, Genre_Streaming.class));
}
}
});
解决方法:
您可以尝试将OnTouchListener与ACTION_DOWN和ACTION_UP结合使用来处理Press / Release事件,而不是OnClickListener.
修改后的代码:
public void setSingleEvent(GridLayout maingrid) {
for (int i = 0; i < maingrid.getChildCount(); i++) {
final CardView cardView = (CardView) maingrid.getChildAt(i);
final int finalI = i;
cardView.setOnTouchListener(new OnTouchListener () {
public boolean onTouch(View view, MotionEvent event) {
if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) {
Toast.makeText(mcontext, "Button: " + finalI, Toast.LENGTH_SHORT).show();
cardView.setCardBackgroundColor(mcontext.getResources().getColor(R.color.buttonPressed));
if (finalI == 0) {
mcontext.startActivity(new Intent(mcontext, Genre_Streaming.class));
}
} else if (event.getAction() == android.view.MotionEvent.ACTION_UP) {
/* Reset Color */
cardView.setCardBackgroundColor(mcontext.getResources().getColor(R.color.red));
}
return true;
}
}
}
链接:http://developer.android.com/reference/android/view/MotionEvent.html#ACTION_UP
标签:android-gridlayout,android-cardview,java,android 来源: https://codeday.me/bug/20191109/2012716.html