android 中自定义组件

1、在开发中我们难免会遇到一些android 自带的组件无法实现的功能,这时候就需要我们重新去定义这些组件,实例实现了一个复合组件(ImageView 与 TextView )的组合,下面就是截图

public class ImageAddText extends LinearLayout implements View.OnClickListener {
    private ImageView img = null;
    private TextView name = null;
    public ImageAddText(Context context) {
        this(context, null);
    }
    public ImageAddText(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        vi.inflate(R.layout.custom_image_textview_activity, this, true);
        this.img = (ImageView) this.findViewById(R.id.img);
        this.name = (TextView) this.findViewById(R.id.name);
        this.img.setOnClickListener(this);
    }
    public void setText(String str, int id) {
        this.img.setBackgroundResource(id);
        this.name.setText(str);
    }
    @Override
    public void onClick(View v) {
        new AlertDialog.Builder(MainApplication.getMainActivity()).setMessage("测试").create().show();
    }
}

custom_image_textview_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical" >
    <ImageView
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

 2、这样定义好了之后,我们就可以在程序中直接引用了,跟用普通组件没什么区别

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值