android::自定义组件

来源:互联网 发布:zblog php自适应模板 编辑:程序博客网 时间:2024/06/17 22:20

 

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