`
lovelease
  • 浏览: 384754 次
社区版块
存档分类
最新评论

Android 含有图片和文字的Button的实现

阅读更多
  要实现一个同时包含图片和文字的按钮,粗糙一点的做法当然是直接画个含有画像和文字的png做button的背景,但是考虑到文字部分的国际化以及灵活性的话,就必须把图片和文字独立开来了。原生的Button控件是做不到的,方法应该有很多,这里介绍我做法,说白了就是一个父View包裹两个子View,父View选用LinearLayout,子View分别是ImageView和TextView。下面看下主要的实现类:
package net.jackie.xxx.view;

import net.jackie.xxx.pickmeupandroid.R;
import android.content.Context;
import android.view.Gravity;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * @author jackie
 *
 */
public class MyImageButton extends LinearLayout {

	private ImageView mButtonImage = null; 
	private TextView mButtonText = null;
	private int textSize = 18;
	
	/**
	 * 
	 * @param context
	 * @param intArray intArray[0] : ImageResourceId; 
	 * intArray[1] : textResourceId; intArray[2] : textSize. Other intArray is useless
	 */
	public MyImageButton(Context context, int... intArray) { 
	    super(context); 
	 
	    // Init instance
	    mButtonImage = new ImageView(context);
	    mButtonText = new TextView(context);
	    
	    int len = intArray.length;
	    if (len >= 1) {
	    	// Set Image Resource
	    	setImageResource(intArray[0]);
	    }
	    if (len >= 2) {
	    	// Set Text
		    setText(intArray[1]);
	    }
	    if (len >= 3) {
	    	// Change text size
	    	textSize = intArray[2];
	    }
	    
	    /** Set Child View(ImageView/TextView) properties */
	    // Set Text Size : default 18
	    setTextSize(textSize);
            // Set ImageView ScaleType : default CENTER_INSIDE(located center, without resize)
	    setImgScaleType(ScaleType.CENTER_INSIDE);
	    LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, 0, 0.5f);
	    // Set ImageView LayoutParams : default half
	    setImgLayoutParams(layoutParams);
	    // Set TextView LayoutParams : default half
	    setTextLayoutParams(layoutParams);
	    // Set Text Gravity : default center
	    setTextGravity(Gravity.CENTER);
	    // Set Text Color : default white
	    setTextColor(0xFFFFFFFF);
	    
	    /** Set Father View(LinearLayout) properties */
	    setClickable(true);
	    setFocusable(true);
		LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT, 1);
//		params.gravity = Gravity.CENTER;
		// Set Father View Orientation : default fulfill
	    setFatherViewLayoutParams(params);
	    // Set Father View Orientation : default my_img_btn_default
	    setFatherViewBgResource(R.drawable.my_img_btn_default);
	    // Set Father View Orientation : default VERTICAL
	    setFatherViewOrientation(LinearLayout.VERTICAL);
	    
	    addView(mButtonImage); 
	    addView(mButtonText); 
	  }

	  /* 
	   * setImageResource
	   */ 
	  public void setImageResource(int resId) { 
	    mButtonImage.setImageResource(resId); 
	  } 
	 
	  /* 
	   * setText
	   */ 
	  public void setText(int resId) { 
	    mButtonText.setText(resId); 
	  } 
	 
	  public void setText(CharSequence buttonText) { 
	    mButtonText.setText(buttonText); 
	  } 
	 
	  /* 
	   * setTextColor
	   */ 
	  public void setTextColor(int color) { 
	    mButtonText.setTextColor(color); 
	  }
	  
	  /* 
	   * setTextSize
	   */ 
	  public void setTextSize(int textSize) { 
	    mButtonText.setTextSize(textSize); 
	  }

	/**
	 * @param layoutParams the layoutParams to set
	 */
	public void setImgLayoutParams(LayoutParams layoutParams) {
		mButtonImage.setLayoutParams(layoutParams);
	}

        /**
	 * Controls how the image should be resized or moved to match the size of this ImageView
	 * 
	 * @param layoutParams the layoutParams to set
	 */
	public void setImgScaleType(ScaleType scaleType) {
		mButtonImage.setScaleType(scaleType);
	}
	
	/**
	 * @param layoutParams the layoutParams to set
	 */
	public void setTextLayoutParams(LayoutParams layoutParams) {
		mButtonText.setLayoutParams(layoutParams);
	}
	
	/**
	 * @param gravity the gravity to set
	 */
	public void setTextGravity(int gravity) {
		mButtonText.setGravity(gravity);
	}
	
	/**
	 * Set Father View LayoutParams. Notice that this method should not be used generally.
	 * 
	 * @param params
	 */
	public void setFatherViewLayoutParams(LayoutParams params) {
		super.setLayoutParams(params);
	}
	
	public void setFatherViewBgResource(int resId) {
		super.setBackgroundResource(resId);
	}
	
	/**
	 * Set orientation of this Linearlayout. Notice that since the default orientation is vertical, 
	 * when you use this method to modify the orientation to horizontal , make sure that you 
	 * also use {@link #setImgLayoutParams(LayoutParams layoutParams)} and 
	 * {@link #setTextLayoutParams(LayoutParams layoutParams)} together, otherwise, 
	 * the button can not be displayed normally
	 * 
	 * @param orientation
	 */
	public void setFatherViewOrientation(int orientation) {
		super.setOrientation(orientation);
	}
	
}


这个类在构造时会生成一个默认的按钮,图片在上,文字在下,还有一些字体等的默认设置,为了尽量做到共通化,又提供了尽可能多的接口以满足不同的式样需求。具体怎么用呢?

1.布局文件中加一个容器,供我们放置自己的ImageButton对象:
<LinearLayout
            android:id="@+id/pickUpBtnContainer"
        	android:orientation="horizontal"
        	android:layout_width="0dip"
            android:layout_height="match_parent"
            android:layout_weight="0.5"
            android:gravity="center" />


2.在Activity中获取到容器,并将我们的ImageButton放进去:
private void initImageButtons() {
		// Get button container
		pickUpBtnContainer = (LinearLayout) findViewById(R.id.pickUpBtnContainer);
		// Get button instance
		pickUpBtn = new MyImageButton(this, R.drawable.test_img, R.string.pickupCtn, 18);
		// Put button instance into button container
		pickUpBtnContainer.addView(pickUpBtn);
		// Set button OnClickListener
		pickUpBtn.setOnClickListener(new Button.OnClickListener(){
			@Override
			public void onClick(View v) {
				// TODO 这里做什么不用说了
//			}
		});
	}

这样就OK了,至于button的背景啊,点击时的效果,和这篇文章关系不大,不过还是把我自己的xml贴上来吧。
my_img_btn_default.xml
<?xml version="1.0" encoding="UTF-8"?>
<selector  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape>
            <gradient android:startColor="@color/my_btn_clicked" android:endColor="@color/my_btn_clicked" android:angle="270" />
            <stroke android:width="1dp" android:color="@color/my_btn_clicked" />
            <padding android:left="10dp" android:top="10dp" android:right="10dp" android:bottom="10dp" />            
        </shape>
    </item>
    <item android:state_focused="true">
        <shape>
            <gradient android:startColor="@color/my_btn_clicked" android:endColor="@color/my_btn_clicked" android:angle="270" />
            <stroke android:width="1dp" android:color="@color/my_btn_clicked" />
            <padding android:left="10dp" android:top="10dp" android:right="10dp" android:bottom="10dp" />            
        </shape>
    </item>
    <item>
        <shape>
            <gradient android:startColor="@color/glb_bg" android:endColor="@color/glb_bg" android:angle="270" />
            <stroke android:width="1dp" android:color="@color/glb_bg" />
            <padding android:left="10dp" android:top="10dp" android:right="10dp" android:bottom="10dp" />            
        </shape>
    </item>
</selector>

如果想要圆角button,在<shape>标签下增加子标签<corners android:radius="5dp" />就可以了,该文件放在drawable下就可使用
分享到:
评论

相关推荐

    C++ 实现可以显示图片和文字的Button控件

    在C++编程中,创建一个可以同时显示图片和文字的Button控件是一项常见的需求,尤其在GUI(图形用户界面)应用程序开发中。本教程将深入探讨如何利用C++来实现这样的功能,主要涉及图像处理、控件封装以及文本渲染等...

    Android编程实现给Button添加图片和文字的方法

    本篇将详细介绍如何在Android编程中为Button控件同时添加图片和文字。 首先,Button的基本使用涉及到XML布局文件中的定义和Java代码中的初始化。在XML布局文件中,我们可以这样创建一个Button: ```xml &lt;Button ...

    Android实现自定义带文字和图片Button的方法

    在Android开发中,自定义带有文字和图片的Button是常见的需求,这可以增强UI的视觉效果和交互性。本文将详细解析两种主要的实现方法:使用系统自带的Button属性以及继承并重绘Button。 首先,我们来看第一种方法...

    android 上传图片和文字

    本文将详细介绍如何在Android中实现这一功能,包括图片的选择、处理、上传,以及文字的编辑和发送。 首先,我们需要一个界面供用户选择图片和输入文字。在Android中,可以使用Intent来调用系统的图库应用让用户选择...

    android 自定义各种风格button

    此外,我们还可以自定义Button的文字样式,包括字体大小、颜色、对齐方式等,以及添加内边距和外边距以改变Button的整体布局效果。例如: ```xml &lt;Button android:layout_width="wrap_content" android:layout_...

    基于Android Studio环境下Button点击事件的实现.pdf

    在 Android Studio 环境下,Button 点击事件的实现是非常重要的,这需要我们对 Android Studio 环境的搭建和 Button 点击事件的实现方式进行深入的分析和讨论。 首先,Android Studio 是基于 IntelliJ IDEA 的开发...

    Android Button事件的实现

    ### Android Button事件的实现 #### 一、简介 在Android应用开发中,`Button`控件是最常用的交互组件之一,用户可以通过点击按钮触发相应的事件处理逻辑。本文将通过一个简单的例子来详细介绍如何在Android应用...

    Android带动态效果的Button(按钮)

    本教程将深入探讨如何在Android中为Button添加动态效果,以提升用户体验和界面的吸引力。 首先,我们从基本的Button说起。在XML布局文件中,可以使用`&lt;Button&gt;`标签来创建一个按钮,例如: ```xml &lt;Button ...

    LinkButton实现图片文字Button效果

    在本教程中,我们将探讨如何利用LinkButton控件来实现一个结合了图片和文字的Button效果,这在网页设计中经常被用于提升用户界面的美观性和交互性。 首先,理解LinkButton的基本概念是至关重要的。LinkButton控件在...

    文字在左图片在右Button

    通过自定义`CompoundDrawable`,可以实现文字在左、图片在右的效果: ```xml android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"&gt; android:...

    Android代码实现图片和文字上下布局

    在Android开发中经常会需要用到带文字和图片的button,下面来给大家介绍使用radiobutton实现图片和文字上下布局或左右布局。代码很简单就不给大家多解释了。 布局文件很简单,用来展示RadioBUtton的使用方法。 &lt...

    android 带文字的图片按钮的实现

    由于Android系统默认的Button控件并未直接提供这样的功能,因此开发者需要采取一些额外的手段来实现这一需求。这里我们将详细探讨两种常用的方法来创建带有文字的图片按钮。 方法一:使用相对布局(RelativeLayout...

    Android自定义Button并设置不同背景图片的方法

    本文实例讲述了Android自定义Button并设置不同背景图片的方法。分享给大家供大家参考,具体如下: 1、自定义MyButton类 public class MyButton extends Button { //This constructormust be public MyButton...

    Android 源码Button 经典实例

    - 在XML布局文件中声明Button,通过`android:text`属性设置文字,`android:id`用于标识,`android:layout_width`和`android:layout_height`设定尺寸。 - 在Java代码中通过`findViewById()`方法获取Button实例,...

    Android炫酷小巧多功能Button

    通过XML中的`&lt;style&gt;`标签定义样式,或者在Java代码中设置`button.setBackgroundResource()`和`button.setTextColor()`等方法实现。 2. **使用Compound Button**: Android中的Compound Button(如Checkbox, ...

    Qt_button文字和图片分开

    "Qt_button文字和图片分开"这个主题就是关于如何在Qt中实现这一目标的。 首先,我们需要了解Qt中的`QPushButton`类,它是Qt Widgets模块中的基础按钮组件。默认情况下,`QPushButton`会将文字和图标一起显示,但...

    Android应用源码之(Button与点击监听器)(.zip

    在Android应用开发中,Button控件是用户...总的来说,理解和掌握Button与点击监听器的使用是Android应用开发的基础,通过阅读和分析提供的源码,你可以更深入地了解Android UI交互的实现细节,并提升自己的编程能力。

    Android ImageButton的使用 及长按Button的实现

    总的来说,`ImageButton`在Android应用开发中扮演着重要的角色,结合点击和长按事件,可以实现丰富的交互功能。通过理解其使用方法和事件处理机制,开发者可以更灵活地设计用户界面,提升用户体验。

    Android-Material-circular-button图片切换和按钮联动效果

    在Android开发中,实现美观且交互性强的用户界面是至关重要的。"Android-Material-circular-button图片切换和按钮联动效果"是一个很好的示例,展示了如何将Material Design风格的圆形按钮与图片切换和按钮联动功能...

Global site tag (gtag.js) - Google Analytics