Android自定义View之不得不知道的文件attrs.xml(自定义属性)

老想着怎么把东西写得能够看懂,才发现会和教是两回事,好了,先看看效果图
在这里插入图片描述
先介绍一下Demoview:第一张图红框内是后续的代码
在这里插入图片描述
布局文件demoview.xml如下;里面放了一个Textview和ImageView。在这里插入图片描述
这个时候如果在Activity中运用的话,就是一个死的view,那么有没有什么办法,能改变里面的东西呢(改变文字&&设置ImageView是否显示)
这里就不得不提到文章标题中的attrs.xml文件了:如下图

在这里插入图片描述
写好后是当然是运用了(其中clickable="true"是设置该控件可以点击,不设置点击变色的背景无效),图片中打错个字,,,,懒得改了

在这里插入图片描述
其中demo_style如下:一般都是放的.9图片,为了方便就放个颜色了
在这里插入图片描述

最后当然是要将自定义的属性实现其功能了(回到第一步中)
在这里插入图片描述
这两句就是取得你在运用中输入的东西了
其中:为了使title相当于TextView中的text:mtv.setText(),将获取的值放入就行了。在这里插入图片描述
那么,那个boolean的值是用来干嘛的呢:控制图片是否显示–> miv.setVisibility(b ? VISIBLE : GONE);如果b为true则显示,为false则不显示。(拓展:了解一下VISIBLE :,GONE,INVISIBLE);

好了现在已经完成了这两个功能了,现在来提一下,点击更换图片
在这里插入图片描述
最后在Activity中调用:
在这里插入图片描述
DemoView.java代码如下:

public class DeomView extends RelativeLayout {
    private ImageView miv;
    private TextView mtv;
    private boolean yfisshow;

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

    public DeomView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);

    }

    public DeomView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        String title = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto", "title");
        boolean b = attrs.getAttributeBooleanValue("http://schemas.android.com/apk/res-auto", "isshow", true);
        View view = View.inflate(context, R.layout.demoview, null);
        addView(view);
        mtv= (TextView) view.findViewById(R.id.tv_togle);
        miv = (ImageView) view.findViewById(R.id.iv_togle);
        miv.setVisibility(b ? VISIBLE : GONE);
        mtv.setText(title);

    }

    //改变状态
    public void setSetting0n(boolean isshow) {
        yfisshow = isshow;
        miv.setImageResource(isshow ? R.mipmap.on : R.mipmap.off);
    }
    //记录状态
    public boolean issetting() {
        return yfisshow;
    }
    public void setbackeguang() {
        //第一次优化
//        if (issetting()){
//            setSetting0n(false);
//        }else{
//           setSetting0n(true);
//        }
        //第二次优化
//          if (yfisshow){
//              setSetting0n(false);
//          }else{
//              setSetting0n(true);
//          }
        //第三次优化
//        if (yfisshow){
//            setSetting0n(!yfisshow);
//        }else{
//            setSetting0n(!yfisshow);
//        }
        setSetting0n(!yfisshow);
    }
}

发布了77 篇原创文章 · 获赞 411 · 访问量 27万+

猜你喜欢

转载自blog.csdn.net/qq_42761395/article/details/99866175