android::自定义组件

 

android中有许多绚丽多彩的按钮,只是靠基本的组件是不能满足的,通过对布局的理解,可以把按钮想象成一个简单的布局文件。在此基础上实现满足要求的按钮。

 

第一步:新建一个XML文件,主要功能是定义按钮的布局,这里我暂时用LinearLayout。在里面添加需要的基本组件。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >
  
  <ImageView
   android:id="@+id/imgview"
   android:layout_alignParentTop="true"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_centerInParent="true"
   android:src="@drawable/icon">
  </ImageView>
  
  <TextView
   android:id="@+id/textview"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_centerInParent="true"
   android:layout_below="@id/imgview">
  </TextView>
</LinearLayout>

第二步:自定义按钮类继承LinearLayout,这个主要作用无非是将XML转化为view。

package com.example.selfdefinetextview;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class ImageTextButton1 extends LinearLayout{


	private ImageView imgView;  
	private TextView  textView;

	public ImageTextButton1(Context context) {
		super(context,null);
	}
	
	public ImageTextButton1(Context context,AttributeSet attributeSet) {
		super(context, attributeSet);
		
		LayoutInflater.from(context).inflate(R.layout.img_text_bt, this,true);//把XML文件实例出来
		
		this.imgView = (ImageView)findViewById(R.id.imgview);
		this.textView = (TextView)findViewById(R.id.textview);
		
		this.setClickable(true);
		this.setFocusable(true);
	}
	
	public void setImgResource(int resourceID) {
		this.imgView.setImageResource(resourceID);
	}
	
	public void setText(String text) {
		this.textView.setText(text);
	}
	
	public void setTextColor(int color) {
		this.textView.setTextColor(color);
	}
	
	public void setTextSize(float size) {
		this.textView.setTextSize(size);
	}
}

第三步:就可以正常使用自己定义的组件了,感觉定义组件含义就是在布局中添加一个小布局。

  <com.example.selfdefinetextview.ImageTextButton1 
   android:id="@+id/bt1"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:background="@drawable/button"
  />




 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值