import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.wanggjie.weishi.R;
/**
* @author 王杰
* @time 2017/2/12 10:08
* @desc ${TODD}
*/
public class SetRelativeLa extends RelativeLayout {
private RelativeLayout mRl_update;
private TextView mMSett_name;
private ImageView mMSett_off_on;
private boolean flag;
//重写父类的构造方法
public SetRelativeLa(Context context) {
this(context, null);
}
//重写父类的构造方法
public SetRelativeLa(Context context, AttributeSet attrs) {
super(context, attrs);
//初始化UI
initView(context);
//加载数据
initData(attrs);
}
public void initData(AttributeSet attrs) {
//自定义的一个View-文本属性
String mytext = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto", "mytext");
mMSett_name.setText(mytext);
//自定义的一个View-背景属性
String mybackgroud = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto", "mybackgroud");
switch (Integer.valueOf(mybackgroud)){
case 0:
mRl_update.setBackgroundResource(R.drawable.first_setting);
break;
case 1:
mRl_update.setBackgroundResource(R.drawable.middle_setting);
break;
case 2:
mRl_update.setBackgroundResource(R.drawable.last_setting);
break;
}
}
public void initView(Context context) {
//通过打气筒把一个布局转换成一个View
View view = View.inflate(context, R.layout.set_relalive_view, this);
mRl_update = (RelativeLayout) view.findViewById(R.id.rl_sett_update);
mMSett_name = (TextView) findViewById(R.id.tv_sett_name);
mMSett_off_on = (ImageView) findViewById(R.id.iv_sett_off_on);
}
//设置点击按钮的时候,设置图片切换
public void setToggleOn(boolean flag){
this.flag= flag;
if(flag) {
mMSett_off_on.setImageResource(R.drawable.on);
}else {
mMSett_off_on.setImageResource(R.drawable.off);
}
}
}
另外的设置:
1,(在res中,创建一个raw文件,然后在该文件中实现以下代码:)
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="SetRelativeLa">
<attr name="mytext" format="string"></attr>
<attr name="mybackgroud">
<enum name="first" value="0"></enum>
<enum name="middle" value="1"></enum>
<enum name="last" value="2"></enum>
</attr>
</declare-styleable>
</resources>
2,(在布局中引用已经设置好的自定义布局类,例子如下:)
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:haha="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<com.wanggjie.weishi.view.SetRelativeLa
android:id="@+id/srl_set_update"
android:layout_width="match_parent"
android:layout_height="38dp"
android:layout_marginTop="8dp"
android:gravity="center"
haha:mytext="开启自动更新"
haha:mybackgroud="first"/>