自定义View步骤

来源:互联网 发布:拉法叶舰案 知乎 编辑:程序博客网 时间:2024/05/01 09:01

1.创建java类

package com.jerry.greentree.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jerry.greentree.R;

import org.w3c.dom.Text;

/**
* Created by jerry on 15/11/3.
*/
public class HotelSelectItemView extends LinearLayout
{
private ImageView mIvHotel = null;
private TextView mTvTitle = null;
private TextView mTvContent = null;

public HotelSelectItemView(Context context)
{
this(context,null);
}

public HotelSelectItemView(Context context, AttributeSet attrs)
{
super(context, attrs);

LayoutInflater inflater = LayoutInflater.from(context);

inflater.inflate(R.layout.select_item_layout,this);

mIvHotel = (ImageView) findViewById(R.id.iv_item);

mTvTitle = (TextView) findViewById(R.id.tv_tip);

mTvContent = (TextView) findViewById(R.id.tv_content);

initAttribute(context, attrs);
}

/**
* 初始化属性
* @param context
* @param attrs
*/
private void initAttribute(Context context, AttributeSet attrs)
{
TypedArray array = context.obtainStyledAttributes(attrs,R.styleable.HotelSelect);

// 获取图片
Drawable icon =
array.getDrawable(R.styleable.HotelSelect_hotel_icon);

mIvHotel.setImageDrawable(icon);


// 获取文本
String title =
array.getString(R.styleable.HotelSelect_hotel_title);

mTvTitle.setText(title);


array.recycle();
}

/**
* 设置条件
* @param content
*/
public void setContent(String content)
{
mTvContent.setText(content);
}

public String getContent()
{
return mTvContent.getText().toString();
}

}

2.写入资源


<resources>
<declare-styleable name="HotelSelect">
<attr name="hotel_icon" format="reference"/>
<attr name="hotel_title" format="string"/>
</declare-styleable>
</resources>



3.布局调用


<com.jerry.greentree.view.HotelSelectItemView
android:id="@+id/item_city"
android:layout_width="match_parent"
android:layout_height="wrap_content"
hotel:hotel_icon="@drawable/img_city"
hotel:hotel_title="@string/city"/>

0 0
原创粉丝点击