在Android Studio中在Card View上添加点击效果波纹效果

问题描述 投票:0回答:3

我已以编程方式添加了名片视图。我只想使其可单击并在单击时显示动画。这是我的代码

CardView cardView = new CardView(this);
LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
cardView.setLayoutParams(layoutParams);
cardView.setRadius(15);
cardView.setPadding(25, 25, 25, 25);
cardView.setCardBackgroundColor(Color.MAGENTA);

TextView textView = new TextView(this);
textView.setLayoutParams(layoutParams);
textView.setText("Programmatically set");
textView.setGravity(Gravity.CENTER);
textView.setTextColor(Color.WHITE);
cardView.addView(textView);
LinearLayout linearLayout = findViewById(R.id.linearLayout1);
linearLayout.addView(cardView);
java android android-studio android-cardview
3个回答
0
投票

您可以使用此:

cardView.setClickable(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    TypedValue typedValue = new TypedValue();
    getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground, typedValue, true);
    cardView.setBackgroundResource(typedValue.resourceId);
}

0
投票

仅使用Material Components Library

cardView.setRippleColor(ContextCompat.getColorStateList(this,R.color.selector_card));

0
投票
int[] attrs = new int[]{R.attr.selectableItemBackground};
TypedArray typedArray = this.obtainStyledAttributes(attrs);
int selectableItemBackground = typedArray.getResourceId(0, 0);
typedArray.recycle();

cardView.setForeground(this.getDrawable(selectableItemBackground));
cardView.setClickable(true);
© www.soinside.com 2019 - 2024. All rights reserved.