• android第一行代码-6.自定义控件的实现


    0.假设一个应用中标题栏控件都是共用的,如果每个activity都需要设置button,绑定方法,那代码就会很臃肿。那我们可以自定义控件,然后继承这个控件就行了。

    自定义控件为TitleLayout,LayoutInflater.from(context).inflate(R.layout.title,this);可以实现动态加载。LayoutInflater是用来找res/layout/下的xml布局文件,并且实例化的,类似于findViewById(),但是findViewById找的是xml布局文件下的具体widget控件(如Button、TextView等)。

    1.控件实现

    public class TitleLayout extends LinearLayout implements View.OnClickListener {
    
        public TitleLayout(Context context,AttributeSet attrs) {
            super(context, attrs);
            LayoutInflater.from(context).inflate(R.layout.title,this);
            Button titleBack = (Button) findViewById(R.id.title_back);
            Button titleEdit = (Button) findViewById(R.id.title_edit);
    
            titleBack.setOnClickListener(this);
            titleEdit.setOnClickListener(this);
        }
    
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.title_back:
                    ((Activity) getContext()).finish();
                    break;
                case R.id.title_edit:
                    Toast.makeText(getContext(),"you click this button",Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }

    2.控件引用

    <?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:orientation="vertical"
        android:weightSum="1">
        
        <activitytest.example.com.uiwidgettest.TitleLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"></activitytest.example.com.uiwidgettest.TitleLayout>
    
    
    </LinearLayout>
  • 相关阅读:
    数据库连接 执行 select 语句
    cygwin完全安装步骤方法(组图)
    Android 8位颜色值和6位颜色值的区别
    执行带参数的sql语句
    [Android环境搭建] 申请Android Map API Key
    调用存储过程
    [Android]应用语言切换的三种方法
    JS 的魅力
    Android工程 引用另外一个Android工程
    使用XML Security验证XML文件的数字签名
  • 原文地址:https://www.cnblogs.com/alexkn/p/5456927.html
Copyright © 2020-2023  润新知