简体   繁体   中英

How to highlight a button in Android with java code?

I've searched around and found the following code, but it's not doing what I want :

  private class ButtonListener implements View.OnClickListener
  {
    public void onClick(View v)
    {
      for (int index = 0; index < GATE.col_count + 1; index++)
        if (gateView.isPinButton((Button) v, index))
        {
          gate.Current_Id = index;
//          ((Button) v).setBackgroundColor(Color.rgb(198,68,18));
          ShapeDrawable shapedrawable = new ShapeDrawable();
          shapedrawable.setShape(new RectShape());
          shapedrawable.getPaint().setColor(Color.rgb(88,236,236));
          shapedrawable.getPaint().setStrokeWidth(10f);
          shapedrawable.getPaint().setStyle(Paint.Style.STROKE);
//          shapedrawable.getPaint().setStyle(Paint.Style.FILL_AND_STROKE);
//          ((Button) v).setBackgroundColor(Color.parseColor("#66FF0000"));
          ((Button) v).setBackground(shapedrawable);
          ((Button) v).getBackground().setColorFilter(0x37000000, PorterDuff.Mode.SRC_ATOP);
          v.invalidate();
          return;
        }
    }
  }

Before a click the button looks like this :

在此处输入图片说明

After the click it looks like this :

在此处输入图片说明

But what I want is to look like this, so the center of the button is still grey like before, yet the border is highlited :

在此处输入图片说明

So what's the right way to do it from the java code ?

这不是最好的解决方案,但作为选项,您可以将按钮放在某个容器中,例如在 FrameLayout 中,将容器的宽度和高度设置为 wrap_content,将背景颜色设置为透明或 @null 并将按钮置于其中心,接下来,您需要为容器设置一些填充,以便容器在按钮后面可见,最后当您单击按钮时,只需在按钮的 onClickListener 中更改容器的背景颜色

I found the answer, it's like this :

      GradientDrawable drawable = new GradientDrawable();
      drawable.setShape(GradientDrawable.RECTANGLE);
      drawable.setStroke(5, Color.rgb(66,218,236));
      drawable.setColor(Color.rgb(214,215,215));
      ((Button) v).setBackground(drawable);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM