来实现功能。
对于自定义属性,大家肯定都不陌生,主要使用在组合控件中,遵循以下几步,就可以实现:4. 在自定义控件CustomView的构造方法中通过TypedArray获取自定义属性
一、在res/values文件下定义一个attrs.xml文件,代码如下:
<declare-styleable name="SettingItemView"> <attr name="mtitle" format="string"/> <attr name="desc_on" format="string"/> <attr name="desc_off" format="string"/> </declare-styleable>
/** * 设置界面每个条目控件 */ public class SettingItemView extends RelativeLayout { TextView tv_title; TextView tv_desc; CheckBox cb_status; private String title; private String desc_on; private String desc_off; //在代码中调用 public SettingItemView(Context context) { super(context); initView(context); } //写在布局文件中调用 public SettingItemView(Context context, AttributeSet attrs) { super(context, attrs); //1,获取控件 initView(context); //2,在自定义组合控件中,可以获得xml中定义的属性值值: TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.SettingItemView); title = typedArray.getString(R.styleable.SettingItemView_mtitle); desc_on = typedArray.getString(R.styleable.SettingItemView_desc_on); desc_off = typedArray.getString(R.styleable.SettingItemView_desc_off); //3,给控件设置属性值 tv_title.setText(title); tv_desc.setText(desc_off); } //获取控件 public void initView(Context context){ View.inflate(context, R.layout.setting_item_view,this); tv_title = (TextView) findViewById(R.id.tv_title); tv_desc = (TextView) findViewById(R.id.tv_desc); cb_status = (CheckBox) findViewById(R.id.cb_status); } public boolean isChecked(){ return cb_status.isChecked(); } public void setChecked(boolean checked){ if(checked){ tv_desc.setText(desc_on); }else{ tv_desc.setText(desc_off); } cb_status.setChecked(checked); } }
三,在布局文件中使用自定义组合控件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:settingitem="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.jiwu.imageviewdemo.MainActivity"> <view.SettingItemView android:id="@+id/setting_iv" android:layout_width="match_parent" android:layout_height="70dp" settingitem:mtitle="接收推送消息" settingitem:desc_on="开" settingitem:desc_off="关" > </LinearLayout>
四,在Activity中使用
SettingItemView setting_iv = (SettingItemView) findViewById(R.id.setting_iv); setting_iv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(setting_iv.isChecked()){ setting_iv.setChecked(false); }else{ setting_iv.setChecked(true); } } });
至此,基本功能已实现,针对不同的设置界面,可以进行定制,如有疑问欢迎留言或加群讨论:196615382,如需源码,点击下载。。。
参考资料:
http://blog.csdn.net/lmj623565791/article/details/45022631
http://www.cnblogs.com/ufocdy/archive/2011/05/27/2060221.html