`
seya
  • 浏览: 363050 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

CustomButton

阅读更多
实现自定义Button有两种方式,
1. 继承View,在里面自己去实现onDraw(), onMeasure(), onClickListener()等方法。这种方式比较灵活,可以实现复杂的需求。
代码样例如下:
package seya.test.comp;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.View;

public class CustomButton extends View{

private final static int WIDTH_PADDING = 8;
private final static int HEIGHT_PADDING = 10;
private final String label;
private final int imageResId;
private final Bitmap image;
//private final InternalListener listenerAdapter = new InternalListener();

public CustomButton(Context context, int resImage, String label)
       {
           super(context);
          this.label = label;
          this.imageResId = resImage;
           this.image = BitmapFactory.decodeResource(context.getResources(),
                  imageResId);
 
           setFocusable(true);
           setBackgroundColor(Color.WHITE);

           //setOnClickListener(listenerAdapter);
           setClickable(true);
       }

@Override
protected void onFocusChanged (boolean gainFocus, int direction, Rect previouslyFocusedRect){
this.setBackgroundColor(Color.GREEN);
}

@Override
protected void onDraw(Canvas canvas)
    {
         Paint textPaint = new Paint();
         textPaint.setColor(Color.BLACK);
         canvas.drawBitmap(image, WIDTH_PADDING / 2, HEIGHT_PADDING / 2, null);
          canvas.drawText(label, WIDTH_PADDING / 2, (HEIGHT_PADDING / 2) +
                  image.getHeight() + 8, textPaint);
     }

@Override
       protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
        {
         setMeasuredDimension(measureWidth(widthMeasureSpec),
                 measureHeight(heightMeasureSpec));
         }

private int measureWidth(int measureSpec)
     {
        int preferred = image.getWidth() * 2;
         return getMeasurement(measureSpec, preferred);
     }
    
     private int measureHeight(int measureSpec)
     {
          int preferred = image.getHeight() * 2;
          return getMeasurement(measureSpec, preferred);
     }
     private int getMeasurement(int measureSpec, int preferred)
     {
              int specSize = MeasureSpec.getSize(measureSpec);
              int measurement = 0;
           
              switch(MeasureSpec.getMode(measureSpec))
             {
                  case MeasureSpec.EXACTLY:
                      // This means the width of this view has been given.
                      measurement = specSize;
                      break;
                 case MeasureSpec.AT_MOST:
                     // Take the minimum of the preferred size and what
                      // we were told to be.
                     measurement = Math.min(preferred, specSize);
                     break;
                default:
                     measurement = preferred;
                    break;
             }
      
             return measurement;
         }

    /* public void setOnClickListener(ClickListener newListener)
          {
              listenerAdapter.setListener(newListener);
          }*/

     public String getLabel()
          {
              return label;
          }
        
          /**
           * Returns the resource id of the image.
           */
          public int getImageResId()
          {
              return imageResId;
          }
         /* private class InternalListener implements View.OnClickListener
               {
                   private ClickListener listener = null;
             
                  
                   public void setListener(ClickListener newListener)
                   {
                       listener = newListener;
                   }
                 
                   @Override
                   public void onClick(View v)
                   {
                       if (listener != null)
                       {
                           listener.onClick(CustomImageButton.this);
                       }
                   }
               }*/
  
}

2. 另一种还是保持原来button的基本功能,只需要改变button在不同状态下的样式,那么就可以这样来做:
在res/drawable下面新建mybutton_background.xml文件,内容如下:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">   
<item android:state_focused="true"      
android:state_pressed="false"    
android:drawable="@drawable/yellow" />  
<item android:state_focused="true"      
android:state_pressed="true"     
android:drawable="@drawable/green" />
<item android:state_focused="false"      
    android:state_pressed="true"
    android:drawable="@drawable/blue" /> 
<item android:drawable="@drawable/grey" />
</selector>
这里面就定义了在不同状态下的显示图片
然后在layout里面定义Button的时候,指定它的background为这个mybutton_background
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <Button android:id="@+id/btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/mybtn"
    android:background="@drawable/mybutton_background"/>
</LinearLayout>
这种方式开发比较简单,适合做一些风格一致的Button,设置成同一个background就可以了。
分享到:
评论

相关推荐

    ios-CustomButton.zip

    在本项目"ios-CustomButton.zip"中,开发者已经创建了一个自定义的按钮类,实现了图片位于上方、文字位于下方,并且具有下划线效果的两种按钮样式。这种自定义的按钮可以为应用的UI提供更多的设计可能性,使其更符合...

    CustomButton.rar

    "CustomButton.rar" 提供了一个在UE4.22版本中的插件,专门用于创建非标准形状的按钮,以满足游戏设计中的独特需求。这个插件允许开发者突破系统默认按钮的限制,设计出更符合游戏风格或交互体验的UI元素。 首先,...

    CustomButton:一个简单的 Andrlid 按钮库,具有波纹效果

    compile ' com.github.whilu.CustomButton:library:1.0.0 ' } 如果它不起作用,请给我。 第2步 首先,在 XML 文件中添加命名空间: xmlns:whilu="http://schemas.android.com/apk/res-auto" 然后,您可以轻松使用...

    CustomButton:macOS应用程序的可自定义按钮

    自定义按钮 ...import CustomButton @main final class AppDelegate : NSObject , NSApplicationDelegate { @IBOutlet weak var window: NSWindow ! func applicationDidFinishLaunching ( _ notificati

    CustomButton:html5画布的可自定义按钮

    我们可以使用`document.getElementById('customButton').getContext('2d')`来获取到这个对象。 在Canvas上绘制按钮,我们首先定义按钮的基本形状。通常,一个按钮可能由矩形、圆角矩形或者更复杂的形状构成。以下是...

    Droid-CustomButton

    【Droid-CustomButton】项目是一个专为Android平台设计的示例工程,它展示了如何在不依赖XML资源或额外图像的情况下实现自定义按钮。这个项目对于开发者来说,是一次了解和学习Android UI自定义的好机会,特别是对于...

    qt4.8.5添加自定义按键

    CustomButton *myButton = new CustomButton(this); connect(myButton, &CustomButton::clicked, this, [this](){ customButtonClickAction(); }); ``` 5. **资源文件和样式表** 如果你想要更复杂的样式,可以...

    Inno自定义界面学习笔记(四)之自定义按钮 的代码资源

    这些图片可以通过设置`CustomButton.Glyph`属性来应用到按钮上,以改变其默认样式。例如,你可以指定一个按下状态的图像,当用户鼠标悬停或点击按钮时显示。 最后,DLL文件可能包含额外的函数库,用于扩展Inno ...

    android 重写控件添加自定义属性

    public class CustomButton extends Button { // 在这里添加新的方法或重写父类的方法 } ``` 接下来,我们讨论如何为自定义控件添加自定义属性。Android提供了XML资源文件来定义控件的属性。自定义属性需要在res/...

    android按钮被选点击得到焦点失去焦点切换图片

    public class CustomButton extends AppCompatButton { private int defaultResId; private int pressedResId; private int focusedResId; private int unfocusedResId; public CustomButton(Context context)...

    Android开发之自定义控件用法详解

    CustomButton customButton = findViewById(R.id.custom_button); customButton.setImageResource(R.drawable.my_image); customButton.setText("点击我"); ``` 通过以上步骤,我们就成功地创建并使用了一个自定义...

    Qt_button文字和图片分开

    CustomButton *myButton = new CustomButton(parentWidget); myButton-&gt;setText("点击我"); // 设置按钮文字 ``` 通过这种方式,你可以实现Qt按钮的文字和图片分开显示,提高界面的可读性和美观度。还可以根据需要...

    Android 中自定义属性(attr.xml,TypedArray)的使用

    `obtainStyledAttributes()` 方法用于创建TypedArray对象,传入的第二个参数是R.styleable.CustomButton,这是我们在attr.xml中定义的styleable资源ID。 四、自定义属性与主题(Theme) 除了在布局文件中直接设置...

    自定义属性

    borderColor = a.getColor(R.styleable.CustomButton_borderColor, Color.TRANSPARENT); borderWidth = a.getDimension(R.styleable.CustomButton_borderWidth, 0); animationDuration = a.getInteger(R....

    ios 自定义uibutton

    let customButton = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50)) ``` 2. **设置按钮类型**:`UIButton`有多种类型,例如`.system`、`.custom`等,可以通过`buttonType`属性设置。 ```swift ...

    自定义Button控件,继承Button控件App源码

    例如,可以添加一个名为`customTextColor`的属性,以便在代码中通过`getAttributes().getColorStateList(R.styleable.CustomButton_customTextColor)`获取并设置按钮文字颜色。 5. **重写`onDraw()`方法**: 如果...

    安卓开发工具类

    CustomButton customButton = findViewById(R.id.custom_button); customButton.setOnBackgroundChangeListener(new BackgroundChangeListener() { @Override public void onBackgroundChanged(int ...

Global site tag (gtag.js) - Google Analytics