[英]How to make button color transparent (or change opacity) when pressed?
我有一个按钮,我想给它 %20 不透明度。 单击后,它必须是旧颜色,没有不透明度或透明度。
这是我的 XML:
<com.example.android.custombutton.CustomButton
android:id="@+id/custombutton_cardselection_turkish_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="@color/blue_button"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:text="@string/nfc_new_turkish_id"
android:textColor="@color/white"
app:layout_constraintBottom_toTopOf="@+id/custombutton_cardselection_passport"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/guideline_cardselection_top" />
我想在 XML 中而不是在 kotlin 部分中更改它。 我怎样才能做到这一点?
使用此代码
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
btn.getBackground().setAlpha(0);
}
});
您还可以在 xml 文件中设置android:background="#10FF0000"
您可以使用OnTouchListener
来实现您所要求的悬停效果。 但是,您无法使用 XML 实现此目的,而需要以编程方式执行此操作。
对于java使用这个
yourBtn.onTouchEvent(new View.OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event) {
yourBtn.getBackground().setAlpha(1);
yourBtn.setBackgroundColor("#ffffff");
if (event.getAction() == MotionEvent.ACTION_UP) {
yourBtn.getBackground().setAlpha((float) 0.2);
}
return false;
}
});
对于 kotlin 使用这个
yourBtn.onTouchEvent(object:View.OnTouchListener() {
fun onTouch(v:View, event:MotionEvent):Boolean {
yourBtn.getBackground().setAlpha(1)
yourBtn.setBackgroundColor("#ffffff")
if (event.getAction() === MotionEvent.ACTION_UP)
{
yourBtn.getBackground().setAlpha(0.2.toFloat())
}
return false
}
})
如果用户点击你的按钮(我的意思是触摸你的按钮),那么它会变得不透明,你可以根据需要设置背景颜色,然后如果用户抬起他的手指,它就会变成 20% 透明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.