自定义属性之LinearLayout ImageView TextView模拟图片文字按钮

一、资源文件:

1、文字选择器:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true" android:color="#FF111111"/>
    <!-- pressed -->
    <item android:state_focused="true" android:color="#FF222222"/>
    <!-- focused -->
    <item android:state_selected="true" android:color="#FF333333"/>
    <!-- selected -->
    <item android:state_active="true" android:color="#FF444444"/>
    <!-- active -->
    <item android:state_checkable="true" android:color="#FF555555"/>
    <!-- checkable -->
    <item android:state_checked="true" android:color="#FF666666"/>
    <!-- checked -->
    <item android:state_enabled="true" android:color="#FF777777"/>
    <!-- enabled -->
    <item android:state_window_focused="true" android:color="#FF888888"/>
    <!-- window_focused -->

</selector>

  2、背景选择器:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <stroke
        android:width="0.5dip"
        android:color="#ff9d9d9d" />

    <corners android:radius="2dip" >
    </corners>

    <padding android:left="5dip" android:top="5dip" android:right="5dip" android:bottom="5dip"/>

    <gradient android:startColor="#ff9d9d9d"
        android:centerColor="#ff9e9e9e"
        android:endColor="#ff9d9d9d"
        />
</shape>
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <stroke
        android:width="0.5dip"
        android:color="#ff505050" />

    <corners android:radius="2dip" >
    </corners>

    <padding android:left="5dip" android:top="5dip" android:right="5dip" android:bottom="5dip"/>

    <gradient android:startColor="#ff404040"
        android:centerColor="#ff383838"
        android:endColor="#ff404040"
        />
</shape>
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/item_background" android:state_enabled="true" android:state_window_focused="false"/>
    <item android:drawable="@drawable/item_background_selected" android:state_pressed="true"/>
    <item android:drawable="@drawable/item_background" android:state_focused="true"/>
    <item android:drawable="@drawable/item_background"/>

</selector>

3、属性文件:

 <!-- imageview text -->
    <declare-styleable name="ImageViewText">
        <attr name="image_size" format="dimension" />
        <attr name="image_src" format="reference" />
        <attr name="textSize" format="dimension" />
        <attr name="text" format="string" />
        <attr name="textMargin" format="dimension" />
        <attr name="textColor" format="reference" />
        <!-- 取值  left top right bottom  -->
        <attr name="text_direction" format="string" />
        <attr name="state_normal" format="color" />
        <attr name="state_pressed" format="color" />
        <attr name="state_selected" format="color" />
        <attr name="view_background" format="reference" />
    </declare-styleable>

二、自定义图片文字:

  1、采用后台代码实现:

public class ImageViewText2 extends LinearLayout {
    private ImageView mImageView;
    private TextView mTextView;

    private View view;

    public ImageViewText2(Context context) {
        super(context);
        initView(context, null);
    }

    // 在父控件中添加android:clickable=“true”
    // android:focusable=“true”,而在子控件中添加android:duplicateParentState=“true”子控件就能获得父控件的点击事件
    public ImageViewText2(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context, attrs);
    }

    private void initView(Context context, AttributeSet attrs) {

        mImageView = new ImageView(context);
        mTextView = new TextView(context);
        view = this;
        view.setBackgroundColor(Color.GRAY);
        this.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
//        this.setPadding(5, 5, 5, 5);

        view.setClickable(true);
        view.setFocusable(true);
        view.setOnClickListener(ocl);
//        view.setOnTouchListener(otl);

        TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.ImageViewText);
        float textSize = typedArray.getDimension(R.styleable.ImageViewText_textSize, 14);
        textSize = textSize/3;
        String text = typedArray.getString(R.styleable.ImageViewText_text);
        float textMarginLeft = typedArray.getDimension(R.styleable.ImageViewText_textMargin, 10);
        float image_size = typedArray.getDimension(R.styleable.ImageViewText_image_size, 10);

        int pressed = typedArray.getColor(R.styleable.ImageViewText_state_pressed, Color.BLACK);
        int normal = typedArray.getColor(R.styleable.ImageViewText_state_normal, Color.BLACK);
        int selected = typedArray.getColor(R.styleable.ImageViewText_state_selected, Color.BLACK);

        int background = typedArray.getResourceId(R.styleable.ImageViewText_view_background, 0);
        int image_src = typedArray.getResourceId(R.styleable.ImageViewText_image_src, 0);
        if (image_src!=0) {
            mImageView.setBackgroundResource(image_src);
        }
        if (background!=0) {
            view.setBackgroundResource(background);
        }

        String text_direction = typedArray.getString(R.styleable.ImageViewText_text_direction);
        mTextView.setText(text);

        mTextView.setTextSize(textSize);
        mTextView.setTextColor(createColorStateList(normal,pressed,selected));

        LayoutParams imageLayoutParams = new LayoutParams((int) image_size,
                (int) image_size);

        mImageView.setLayoutParams(imageLayoutParams);

        typedArray.recycle();//

        LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT);
        if (TextDirection.LEFT.equals(text_direction)) {
            this.setOrientation(HORIZONTAL);
            params.rightMargin = (int) textMarginLeft;
            mTextView.setLayoutParams(params);
            addView(mTextView);
            addView(mImageView);

        } else if (TextDirection.RIGHT.equals(text_direction)) {
            this.setOrientation(HORIZONTAL);
            params.leftMargin = (int) textMarginLeft;
            mTextView.setLayoutParams(params);
            addView(mImageView);
            addView(mTextView);
        } else if (TextDirection.TOP.equals(text_direction)) {
            this.setOrientation(VERTICAL);
            params.bottomMargin = (int) textMarginLeft;
            mTextView.setLayoutParams(params);
            addView(mTextView);
            addView(mImageView);
        } else if (TextDirection.BOTTOM.equals(text_direction)) {
            this.setOrientation(VERTICAL);
            params.topMargin = (int) textMarginLeft;
            mTextView.setLayoutParams(params);
            addView(mImageView);
            addView(mTextView);
        }
    }

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

//    public OnTouchListener otl = new OnTouchListener() {
//        @Override
//        public boolean onTouch(View v, MotionEvent event) {
//            if (event.getAction() == MotionEvent.ACTION_DOWN) {
//                view.setBackgroundColor(context.getResources().getColor(
//                        R.color.blue_shallow));
//            } else if (event.getAction() == MotionEvent.ACTION_UP) {
//                view.setBackgroundColor(Color.GRAY);
//            }
//            return false;
//        }
//    };

    public OnClickListenerView listener;

    public void setOnClickListener(OnClickListenerView listenerView) {
        this.listener = listenerView;
    }

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

    /** 对TextView设置不同状态时其文字颜色。 */
    private ColorStateList createColorStateList(int normal, int pressed,
            int selected) {
        int[] colors = new int[] { pressed,  selected, normal };
        int[][] states = new int[3][];
        states[0] = new int[] { android.R.attr.state_pressed,
                android.R.attr.state_enabled };
        states[1] = new int[] { android.R.attr.selectable,
                android.R.attr.state_focused };
        states[2] = new int[] {};

        ColorStateList colorList = new ColorStateList(states, colors);
        return colorList;
    }

    /** 设置Selector。 */
    public static StateListDrawable newSelector(Context context, int idNormal,
            int idPressed, int idFocused, int idUnable) {
        StateListDrawable bg = new StateListDrawable();
        Drawable normal = idNormal == -1 ? null : context.getResources()
                .getDrawable(idNormal);
        Drawable pressed = idPressed == -1 ? null : context.getResources()
                .getDrawable(idPressed);
        Drawable focused = idFocused == -1 ? null : context.getResources()
                .getDrawable(idFocused);
        Drawable unable = idUnable == -1 ? null : context.getResources()
                .getDrawable(idUnable);
        // View.PRESSED_ENABLED_STATE_SET
        bg.addState(new int[] { android.R.attr.state_pressed,
                android.R.attr.state_enabled }, pressed);
        // View.ENABLED_FOCUSED_STATE_SET
        bg.addState(new int[] { android.R.attr.state_enabled,
                android.R.attr.state_focused }, focused);
        // View.ENABLED_STATE_SET
        bg.addState(new int[] { android.R.attr.state_enabled }, normal);
        // View.FOCUSED_STATE_SET
        bg.addState(new int[] { android.R.attr.state_focused }, focused);
        // View.WINDOW_FOCUSED_STATE_SET
        bg.addState(new int[] { android.R.attr.state_window_focused }, unable);
        // View.EMPTY_STATE_SET
        bg.addState(new int[] {}, normal);
        return bg;
    }

    public class TextDirection {
        public static final String LEFT = "left";
        public static final String TOP = "top";
        public static final String RIGHT = "right";
        public static final String BOTTOM = "bottom";
    }
}

  2、采用后台代码和布局文件:

注意属性duplicateParentState的使用

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#ffffffff"
    android:orientation="horizontal"
    android:gravity="center_vertical"
    android:padding="5dip"
      >

    <ImageView
        android:id="@+id/iv_button_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/home" />

    <TextView
        android:id="@+id/tv_button_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@drawable/text_wbcolor_selector"
        android:duplicateParentState="true"
        android:text="收藏" />

</LinearLayout>
package com.example.customui.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
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.LinearLayout;
import android.widget.TextView;

import com.example.customui.R;

public class ImageViewText extends LinearLayout  {
    private Context context;
    private LayoutInflater inflater;
    private ImageView mImageView;
    private TextView mTextView;

    private View view;

    public ImageViewText(Context context) {
        super(context);
        initView(context,null);
    }

    //在父控件中添加android:clickable=“true” android:focusable=“true”,而在子控件中添加android:duplicateParentState=“true”子控件就能获得父控件的点击事件
    public ImageViewText(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context,attrs);
    }

    private void initView(Context context, AttributeSet attrs) {
        this.context = context;
        inflater = LayoutInflater.from(context);
        view = inflater.inflate(R.layout.widget_image_text, null);

        mImageView = (ImageView) view.findViewById(R.id.iv_button_icon);
        mTextView = (TextView) view.findViewById(R.id.tv_button_text);

        this.setGravity(Gravity.CENTER_VERTICAL|Gravity.LEFT);
        this.setOrientation(HORIZONTAL);
        this.setPadding(5, 5, 5, 5);

        view.setClickable(true);
        view.setFocusable(true);
        view.setOnClickListener(ocl);
        view.setOnTouchListener(otl);

        TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.ImageViewText);
        float textSize = a.getDimension(R.styleable.ImageViewText_textSize, 14);
        textSize = textSize/3;
        String text = a.getString(R.styleable.ImageViewText_text);
        float textMarginLeft = a.getDimension(R.styleable.ImageViewText_textMargin, 10);
        float image_size = a.getDimension(R.styleable.ImageViewText_image_size, 10);

        mTextView.setText(text);
        mTextView.setTextSize(textSize);

        LayoutParams params  = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        params.leftMargin = (int) textMarginLeft;
        mTextView.setLayoutParams(params);
        mImageView.getLayoutParams().height=(int) image_size;
        mImageView.getLayoutParams().width=(int) image_size;
        mImageView.setImageResource(R.drawable.home);

        a.recycle();//
        view.setBackgroundColor(Color.GRAY);
        addView(view,new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

    }

    public OnClickListener ocl = new OnClickListener() {
        @Override
        public void onClick(View v) {
//            listener.onClick(v);
        }
    };

    /**
     * 设置颜色
     */
    public OnTouchListener otl = new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                view.setBackgroundColor(context.getResources().getColor(R.color.blue_shallow));
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                view.setBackgroundColor(Color.GRAY);
            }
            return false;
        }
    };

    public OnClickListenerView listener;

    public void setOnClickListener(OnClickListenerView listenerView){
        this.listener = listenerView;
    }

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

}
时间: 2024-12-29 13:10:14

自定义属性之LinearLayout ImageView TextView模拟图片文字按钮的相关文章

Android TextView(同时显示图片+文字)

见上图:需要图片和文字 在一起 之前的做法是用两个控件组成 <LinearLayout> <ImageView /> <TextView /> </LinearLayout> 今天读人家的源码,发现原来一个TextView就可以实现: <TextView android:id="@+id/btn_middle" style="@style/style_topbar_textview_shadow" android

Android TextView中有图片有文字混合排列

1.使用html.fromHtml 2.新建ImageGetter 3.使用<img src>标签 demo: 1.设置文字 ((TextView) findViewById(R.id.tv_gradlist_calorie_desc)).setText(Html .fromHtml(descString(), getImageGetterInstance(), null)); 2.获取文字 /** * 字符串 * * @return */ private String descString(

Android自定义“图片+文字”控件四种实现方法之 二--------个人最推荐的一种

http://blog.csdn.net/yanzi1225627/article/details/8633872 第二种方法也要新建一个图片+文字的xml布局文件,然后写一个类继承自LinearLayout.在主程序里实例化并设置相应参数.这种方式也是我最推荐的一种. 第一部分:myimgbtn_layout.xml [html] view plaincopyprint? <?xml version="1.0" encoding="utf-8"?> &

基于Android4.0ListView从网络获取图片文字资源显示

平时的一些Android学习视频中,他们都是基于Android的去使用ListView,我看到都是会在UI线程中去访问网络获取数据,但是这在Android4.0之后是行不通的. 首先我们来理一下思绪: 我们需要从网络上下载一份xml数据,里面包含了需要显示的文字和图片路径.所以我们首先需要的就是先去下载数据,下载数据完成之后再在Adapter中显示图片的时候去下载图片,然后显示出来.这是基本的思路.但是做着做着会发现一些问题,比如,我们如何能保证数据下载完全,才去绑定适配器和数据他们.然后假如我

Android - TextView添加图片

TextView添加图片 本文地址:http://blog.csdn.net/caroline_wendy Android UI设计时,经常需要在文字周围添加图片. 比较简单的方法是直接使用Layout把View组合到一起: <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/icon_ho

android linearlayout imageview置顶摆放

在练习android时,想在Linearlayout内放一图片,使其图片置顶,预期效果是这样的: 但xml代码imageview写成这样后, <ImageView android:layout_width="match_parent" android:layout_height="wrap_content" android:src="@drawable/moegirl_help" /> 效果却是这样的 试了谢方法,包括改为Relati

iOS UIButton 设置图片文字垂直排列

在实际的iOS项目开发中,我们经常需要改变系统的控件的样式,自己定义一个,同样的当我们发现系统自带的某些方法不好使时,我们也会想到重写这个方法. 本文主要记录笔者设置UIButton图片文字垂直排列的方法,最终解决了在图片和文字垂直排列的情况下,如果文字长度变化会导致图片位置变动的问题,对 于此问题网上有比较多的做法,我就不多说了,在此记录这点细节仅为加深印象并方便以后查阅.如有纰漏还请见谅 方案一:通过调整按钮图片和文字的内边距 UIEdgeInsets typedef struct UIEd

UIButton图片文字控件位置自定义(图片居右文字居左、图片居中文字居中、图片居左文字消失等)

在开发中经常会碰到需要对按钮中的图片文字位置做调整的需求.第一种方式是通过设置按钮中图片文字的偏移量.通过方法setTitleEdgeInsets和setImageEdgeInsets实现 代码如下: /*!**方式一***/ - (void)updateBtnStyle_rightImage:(UIButton *)btn { CGFloat btnImageWidth = btn.imageView.bounds.size.width; CGFloat btnLabelWidth = btn

UIButton 设置图片文字垂直居中排列

#pragma mark 按钮图片文字垂直居中排列 -(void)setButtonContentCenter:(UIButton *)button { CGSize imgViewSize,titleSize,btnSize; UIEdgeInsets imageViewEdge,titleEdge; CGFloat heightSpace = 10.0f; //设置按钮内边距 imgViewSize = button.imageView.bounds.size; titleSize = bu