Android 中的圆形按钮 [英] Rounded Button in Android

查看:47
本文介绍了Android 中的圆形按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Android 程序中创建圆形按钮.我看过如何创建带有圆角的 EditText?

I want to create rounded buttons in an Android program. I have looked at How to create EditText with rounded corners?

我想要实现的是:

  1. 圆边按钮
  2. 更改不同状态下的按钮背景/外观(如 Onclick、Focus)
  3. 使用我自己的 PNG 作为背景,而不是创建形状.

推荐答案

你可以做一个圆角按钮,而无需求助于 ImageView.

You can do a rounded corner button without resorting to an ImageView.

背景选择器资源,button_background.xml:

<?xml version="1.0" encoding="utf-8" ?> 
     <selector xmlns:android="http://schemas.android.com/apk/res/android">
     <!--  Non focused states 
      --> 
      <item android:state_focused="false" android:state_selected="false" android:state_pressed="false" android:drawable="@drawable/button_unfocused" /> 
      <item android:state_focused="false" android:state_selected="true" android:state_pressed="false" android:drawable="@drawable/button_unfocused" /> 
     <!--  Focused states 
      --> 
      <item android:state_focused="true" android:state_selected="false" android:state_pressed="false" android:drawable="@drawable/button_focus" /> 
      <item android:state_focused="true" android:state_selected="true" android:state_pressed="false" android:drawable="@drawable/button_focus" /> 
     <!--  Pressed 
      --> 
      <item android:state_pressed="true" android:drawable="@drawable/button_press" /> 
    </selector>

对于每个状态,一个可绘制的资源,例如button_press.xml:

For each state, a drawable resource, e.g. button_press.xml:

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
  <stroke android:width="1dp" android:color="#FF404040" /> 
  <corners android:radius="6dp" /> 
  <gradient android:startColor="#FF6800" android:centerColor="#FF8000" android:endColor="#FF9700" android:angle="90" /> 
</shape>

注意 corners 元素,这会让你得到圆角!

Note the corners element, this gets you rounded corners!

然后在按钮上设置背景drawable:

Then set the background drawable on the button:

android:background="@drawable/button_background"

EDIT (9/2018):同样的技术可用于创建圆形按钮.圆实际上只是一个方形按钮,半径大小设置为正方形边长的 1/2

EDIT (9/2018): The same technique can be used to create a circular button. A circle is really just a square button with radius size set to 1/2 the side of the square

此外,在上面的示例中,strokegradient 不是必需的元素,它们只是示例和您可以看到圆角的方式形状

Additionally, in the example above the stroke and gradient aren't necessary elements, they are just examples and ways that you'll be able to see the rounded corner shape

这篇关于Android 中的圆形按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆