全网整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:400-708-3566

Android自定义控件实现icon+文字的多种效果

今天给大家带来一个很简单但是很常用的控件ButtonExtendM,在开发中我们经常会用到图片加文字的组合控件,像这样:

以上图片都是从微信上截取的。(暂时没有找到icon在下,文字在上的例子)

下面我们通过一个控件来实现上下左右全部的样式,只需改动一个属性值即可改变icon的位置,是不是很方便,先看下demo效果图:

没错上图的三种不同的样式都是通过同一个控件实现的,下面我们看下代码

第一步 自定义属性 

在res/values/目录下新建attrs.xml文件,
添加如下属性

<attr name="backColor" format="color" />
 <attr name="backColorPress" format="color" />
 <attr name="textColor" format="color" />
 <attr name="textColorPress" format="color" />

 <declare-styleable name="ButtonExtendM">
  <attr name="backColor"/>
  <attr name="backColorPress"/>
  <attr name="textColor"/>
  <attr name="textColorPress"/>
  <attr name="iconDrawable" format="reference" />
  <attr name="iconDrawablePress" format="reference" />
  <attr name="text" format="string" />
  <attr name="textSize" format="float" />
  <attr name="spacing" format="dimension" />
  <attr name="style">
   <enum name="iconLeft" value="0" />
   <enum name="iconRight" value="1" />
   <enum name="iconUp" value="2" />
   <enum name="iconBottom" value="3" />
  </attr>
 </declare-styleable>

第二步 新建布局文件view_button_extend_m.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content">

 <ImageView
  android:id="@+id/iv_icon"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"/>

 <TextView
  android:id="@+id/tv_content"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:visibility="gone"
  android:text="@string/button_extend_m_default_text"/>

</RelativeLayout>

第三步 新建ButtonExtendM.java继承RelativeLayout

package com.landptf.view;

import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.landptf.R;
import com.landptf.util.ConvertM;

/**
 * Created by landptf on 2016/10/31.
 * 扩展Button,支持文字和icon分上下左右四种方式显示
 * 默认为左右结构,图片在左,文字在右
 */
public class ButtonExtendM extends RelativeLayout {
 /**
  * 左右结构,图片在左,文字在右
  */
 public static final int STYLE_ICON_LEFT = 0;
 /**
  * 左右结构,图片在右,文字在左
  */
 public static final int STYLE_ICON_RIGHT = 1;
 /**
  * 上下结构,图片在上,文字在下
  */
 public static final int STYLE_ICON_UP = 2;
 /**
  * 上下结构,图片在下,文字在上
  */
 public static final int STYLE_ICON_DOWN = 3;

 /**
  * 定义控件
  */
 private ImageView ivIcon;
 private TextView tvContent;
 /**
  * 上下文
  */
 private Context mContext;
 /**
  * View的背景色
  */
 private int backColor = 0;
 /**
  * View被按下时的背景色
  */
 private int backColorPress = 0;
 /**
  * icon的背景图片
  */
 private Drawable iconDrawable = null;
 /**
  * icon被按下时显示的背景图片
  */
 private Drawable iconDrawablePress = null;
 /**
  * View文字的颜色
  */
 private ColorStateList textColor = null;
 /**
  * View被按下时文字的颜色
  */
 private ColorStateList textColorPress = null;
 /**
  * 两个控件之间的间距,默认为8dp
  */
 private int spacing = 8;
 /**
  * 两个控件的位置结构
  */
 private int mStyle = STYLE_ICON_LEFT;
 /**
  * 标示onTouch方法的返回值,用来解决onClick和onTouch冲突问题
  */
 private boolean isCost = true;

 private OnClickListener onClickListener = null;

 public interface OnClickListener {
  void onClick(View v);
 }

 /**
  * 设置View的Click事件
  *
  * @param l
  */
 public void setOnClickListener(OnClickListener l) {
  this.onClickListener = l;
  isCost = false;
 }

 public ButtonExtendM(Context context) {
  super(context);
  mContext = context;
 }

 public ButtonExtendM(Context context, AttributeSet attrs) {
  this(context, attrs, 0);
 }

 public ButtonExtendM(Context context, AttributeSet attrs, int defStyle) {
  super(context, attrs, defStyle);
  mContext = context;
  init(context, attrs, defStyle);

 }

 private void init(Context context, AttributeSet attrs, int defStyle) {
  //加载布局
  LayoutInflater.from(context).inflate(R.layout.view_button_extend_m, this, true);
  //初始化控件
  ivIcon = (ImageView) findViewById(R.id.iv_icon);
  tvContent = (TextView) findViewById(R.id.tv_content);
  setGravity(Gravity.CENTER);
  TypedArray a = getContext().obtainStyledAttributes(
    attrs, R.styleable.ButtonExtendM, defStyle, 0);
  if (a != null) {
   //设置背景色
   ColorStateList colorList = a.getColorStateList(R.styleable.ButtonExtendM_backColor);
   if (colorList != null) {
    backColor = colorList.getColorForState(getDrawableState(), 0);
    if (backColor != 0) {
     setBackgroundColor(backColor);
    }
   }
   //记录View被按下时的背景色
   ColorStateList colorListPress = a.getColorStateList(R.styleable.ButtonExtendM_backColorPress);
   if (colorListPress != null) {
    backColorPress = colorListPress.getColorForState(getDrawableState(), 0);
   }
   //设置icon
   iconDrawable = a.getDrawable(R.styleable.ButtonExtendM_iconDrawable);
   if (iconDrawable != null) {
    ivIcon.setImageDrawable(iconDrawable);
   }
   //记录View被按下时的icon的图片
   iconDrawablePress = a.getDrawable(R.styleable.ButtonExtendM_iconDrawablePress);
   //设置文字的颜色
   textColor = a.getColorStateList(R.styleable.ButtonExtendM_textColor);
   if (textColor != null) {
    tvContent.setTextColor(textColor);
   }
   //记录View被按下时文字的颜色
   textColorPress = a.getColorStateList(R.styleable.ButtonExtendM_textColorPress);
   //设置显示的文本内容
   String text = a.getString(R.styleable.ButtonExtendM_text);
   if (text != null) {
    //默认为隐藏的,设置文字后显示出来
    tvContent.setVisibility(VISIBLE);
    tvContent.setText(text);
   }
   //设置文本字体大小
   float textSize = a.getFloat(R.styleable.ButtonExtendM_textSize, 0);
   if (textSize != 0) {
    tvContent.setTextSize(textSize);
   }
   //设置两个控件之间的间距
   spacing = a.getDimensionPixelSize(R.styleable.ButtonExtendM_spacing, ConvertM.dp2px(context, 8));
   //设置两个控件的位置结构
   mStyle = a.getInt(R.styleable.ButtonExtendM_style, 0);
   setIconStyle(mStyle);
   a.recycle();
  }

  setOnTouchListener(new OnTouchListener() {
   @Override
   public boolean onTouch(View arg0, MotionEvent event) {
    //根据touch事件设置按下抬起的样式
    return setTouchStyle(event.getAction());
   }
  });

  setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
    if (onClickListener != null) {
     onClickListener.onClick(v);
    }
   }
  });
 }

 /**
  * 根据按下或者抬起来改变背景和文字样式
  *
  * @param state
  * @return isCost
  */
 private boolean setTouchStyle(int state) {
  if (state == MotionEvent.ACTION_DOWN) {
   if (backColorPress != 0) {
    setBackgroundColor(backColorPress);
   }
   if (iconDrawablePress != null) {
    ivIcon.setImageDrawable(iconDrawablePress);
   }
   if (textColorPress != null) {
    tvContent.setTextColor(textColorPress);
   }
  }
  if (state == MotionEvent.ACTION_UP) {
   if (backColor != 0) {
    setBackgroundColor(backColor);
   }
   if (iconDrawable != null) {
    ivIcon.setImageDrawable(iconDrawable);
   }
   if (textColor != null) {
    tvContent.setTextColor(textColor);
   }
  }
  return isCost;
 }

 /**
  * 设置图标位置
  * 通过重置LayoutParams来设置两个控件的摆放位置
  * @param style
  */
 public void setIconStyle(int style) {
  mStyle = style;
  RelativeLayout.LayoutParams lp;
  switch (style) {
   case STYLE_ICON_LEFT:
    lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    lp.addRule(RelativeLayout.CENTER_VERTICAL);
    ivIcon.setLayoutParams(lp);
    lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    lp.addRule(RelativeLayout.CENTER_VERTICAL);
    lp.addRule(RelativeLayout.RIGHT_OF, ivIcon.getId());
    lp.leftMargin = spacing;
    tvContent.setLayoutParams(lp);
    break;
   case STYLE_ICON_RIGHT:
    lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    lp.addRule(RelativeLayout.CENTER_VERTICAL);
    tvContent.setLayoutParams(lp);
    lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    lp.addRule(RelativeLayout.CENTER_VERTICAL);
    lp.addRule(RelativeLayout.RIGHT_OF, tvContent.getId());
    lp.leftMargin = spacing;
    ivIcon.setLayoutParams(lp);
    break;
   case STYLE_ICON_UP:
    lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
    ivIcon.setLayoutParams(lp);
    lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
    lp.addRule(RelativeLayout.BELOW, ivIcon.getId());
    lp.leftMargin = spacing;
    tvContent.setLayoutParams(lp);
    break;
   case STYLE_ICON_DOWN:
    lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
    tvContent.setLayoutParams(lp);
    lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
    lp.addRule(RelativeLayout.BELOW, tvContent.getId());
    lp.leftMargin = spacing;
    ivIcon.setLayoutParams(lp);
    break;
   default:
    break;
  }
 }

 /**
  * 设置View的背景色
  *
  * @param backColor
  */
 public void setBackColor(int backColor) {
  this.backColor = backColor;
  setBackgroundColor(backColor);
 }

 /**
  * 设置View被按下时的背景色
  *
  * @param backColorPress
  */
 public void setBackColorPress(int backColorPress) {
  this.backColorPress = backColorPress;
 }

 /**
  * 设置icon的图片
  *
  * @param iconDrawable
  */
 public void setIconDrawable(Drawable iconDrawable) {
  this.iconDrawable = iconDrawable;
  ivIcon.setImageDrawable(iconDrawable);
 }

 /**
  * 设置View被按下时的icon的图片
  *
  * @param iconDrawablePress
  */
 public void setIconDrawablePress(Drawable iconDrawablePress) {
  this.iconDrawablePress = iconDrawablePress;
 }

 /**
  * 设置文字的颜色
  *
  * @param textColor
  */
 public void setTextColor(int textColor) {
  if (textColor == 0) return;
  this.textColor = ColorStateList.valueOf(textColor);
  tvContent.setTextColor(this.textColor);
 }

 /**
  * 设置View被按下时文字的颜色
  *
  * @param textColorPress
  */
 public void setTextColorPress(int textColorPress) {
  if (textColorPress == 0) return;
  this.textColorPress = ColorStateList.valueOf(textColorPress);
 }

 /**
  * 设置显示的文本内容
  *
  * @param text
  */
 public void setText(CharSequence text) {
  //默认为隐藏的,设置文字后显示出来
  tvContent.setVisibility(VISIBLE);
  tvContent.setText(text);
 }

 /**
  * 获取显示的文本
  *
  * @return
  */
 public String getText() {
  return tvContent.getText().toString();
 }

 /**
  * 设置文本字体大小
  *
  * @param size
  */
 public void setTextSize(float size) {
  tvContent.setTextSize(size);
 }

 /**
  * 设置两个控件之间的间距
  *
  * @param spacing
  */
 public void setSpacing(int spacing) {
  this.spacing = ConvertM.dp2px(mContext, spacing);
  //设置完成后刷新一下两个控件的结构,避免先执行了setIconStyle后,setSpacing不生效
  setIconStyle(mStyle);
 }

}

代码注释基本可以看懂具体的实现,接下来主要看下如何使用

在layout里直接引用ButtonExtendM即可,注意要添加

xmlns:landptf="http://schemas.android.com/apk/res-auto"

<com.landptf.view.ButtonExtendM
 android:id="@+id/bem_back"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerVertical="true"
 android:layout_marginLeft="8dp"
 landptf:iconDrawable="@drawable/title_back"
 landptf:iconDrawablePress="@drawable/title_back_selected"
 landptf:textColor="@android:color/white"
 landptf:spacing="4dp"
 landptf:text="返回"/>

这个是实现的菜单栏的返回按钮,左右结构,icon在左为默认样式,注意一下*Press的属性,主要是用来设置控件被按下后的效果的。

再来看一个上下结构的

<com.landptf.view.ButtonExtendM
 android:layout_width="0dp"
 android:layout_height="match_parent"
 android:layout_weight="1"
 landptf:iconDrawable="@drawable/icon_home_page"
 landptf:text="首页"
 landptf:style="iconUp" />

只需要设置landptf:style即可,同时也可以通过java代码实现

setIconStyle(ButtonExtendM.STYLE_ICON_UP)

全部代码已托管到开源中国的码云上,欢迎下载,地址:https://git.oschina.net/landptf/landptf.git

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


# Android  # icon+  # 文字效果  # Android Secret Code(输入字符弹出手机信息)详解  # Android BadgeView红点更新信息提示示例代码  # Android中获取资源 id 及资源 id 的动态获取  # android虚拟键盘弹出遮挡登陆按钮问题的解决方法  # Android自定义控件实现底部菜单(下)  # Android编程实现自定义ProgressBar样式示例(背景色及一级、二级进度条颜色)  # Android编程获取设备MAC地址的实现方法  # Android 获取手机信息实例详解  # 按下  # 背景色  # 默认为  # 在上  # 上下左右  # 都是  # 只需  # 是从  # 可以通过  # 给大家  # 很简单  # 再来  # 三种  # 自定义  # 只需要  # 四种  # 没有找到  # 来实现  # 首页  # 很方便 


相关文章: 高防网站服务器:DDoS防御与BGP线路的AI智能防护方案  如何挑选最适合建站的高性能VPS主机?  制作农业网站的软件,比较好的农业网站推荐一下?  小自动建站系统:AI智能生成+拖拽模板,多端适配一键搭建  如何在七牛云存储上搭建网站并设置自定义域名?  已有域名和空间,如何快速搭建网站?  如何用IIS7快速搭建并优化网站站点?  用v-html解决Vue.js渲染中html标签不被解析的问题  网站制作网站,深圳做网站哪家比较好?  建站主机解析:虚拟主机配置与服务器选择指南  青浦网站制作公司有哪些,苹果官网发货地是哪里?  高端智能建站公司优选:品牌定制与SEO优化一站式服务  详解免费开源的DotNet二维码操作组件ThoughtWorks.QRCode(.NET组件介绍之四)  东莞市网站制作公司有哪些,东莞找工作用什么网站好?  微信推文制作网站有哪些,怎么做微信推文,急?  子杰智能建站系统|零代码开发与AI生成SEO优化指南  网站制作的方法有哪些,如何将自己制作的网站发布到网上?  建站VPS选购需注意哪些关键参数?  网站建设制作需要多少钱费用,自己做一个网站要多少钱,模板一般多少钱?  制作无缝贴图网站有哪些,3dmax无缝贴图怎么调?  如何通过山东自助建站平台快速注册域名?  制作网站的公司有哪些,做一个公司网站要多少钱?  小型网站制作HTML,*游戏网站怎么搭建?  专业企业网站设计制作公司,如何理解商贸企业的统一配送和分销网络建设?  如何通过宝塔面板实现本地网站访问?  如何快速搭建自助建站会员专属系统?  东莞专业网站制作公司有哪些,东莞招聘网站哪个好?  存储型VPS适合搭建中小型网站吗?  rsync同步时出现rsync: failed to set times on “xxxx”: Operation not permitted  ppt制作免费网站有哪些,ppt模板免费下载网站?  建站与域名管理如何高效结合?  制作网站的软件免费下载,免费制作app哪个平台好?  建站主机选哪种环境更利于SEO优化?  建站之星免费版是否永久可用?  弹幕视频网站制作教程下载,弹幕视频网站是什么意思?  导航网站建站方案与优化指南:一站式高效搭建技巧解析  零服务器AI建站解决方案:快速部署与云端平台低成本实践  网站制作模板下载什么软件,ppt模板免费下载网站?    建站之星如何助力企业快速打造五合一网站?  如何用西部建站助手快速创建专业网站?  网站制作公司,橙子建站是合法的吗?  兔展官网 在线制作,怎样制作微信请帖?  如何快速搭建安全的FTP站点?  头像制作网站在线观看,除了站酷,还有哪些比较好的设计网站?  如何有效防御Web建站篡改攻击?  建站上传速度慢?如何优化加速网站加载效率?  学校免费自助建站系统:智能生成+拖拽设计+多端适配  如何在Windows 2008云服务器安全搭建网站?  如何在万网ECS上快速搭建专属网站? 

您的项目需求

*请认真填写需求信息,我们会在24小时内与您取得联系。