【问题标题】:How to make button color transparent (or change opacity) when pressed?按下时如何使按钮颜色透明(或更改不透明度)?
【发布时间】:2020-10-16 12:35:39
【问题描述】:

我有一个按钮,我想给它 %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 部分。我该怎么做?

【问题讨论】:

    标签: android xml button


    【解决方案1】:

    使用此代码

    btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                btn.getBackground().setAlpha(0);
            }
        });
    

    你也可以在xml文件中设置android:background="#10FF0000"

    【讨论】:

    • 这不是我问的。它永久使其透明,我只想在触摸时使其透明。然后当我移开手指时,它必须是它的旧颜色
    【解决方案2】:

    您可以使用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% 透明。

    【讨论】:

      猜你喜欢
      • 2014-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-05
      • 1970-01-01
      • 2019-12-13
      • 2021-08-01
      • 2014-09-05
      相关资源
      最近更新 更多