zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    又见JavaWeb的中文乱码
    Java 中文字符串编码之GBK转UTF-8
    关于Java项目打包
    FreeSWITCH无法读取wav文件
    CentOS 7 最小化安装的网络配置
    虚拟机无法使用网卡桥接模式
    阿里云建站流程
    Spring MVC无法获取ajax POST的参数和值
    Mysql ERROR 1064 (42000)
    eclipse创建java类时自动添加注释
  • 原文地址:https://www.cnblogs.com/alexkn/p/5456927.html
Copyright © 2011-2022 走看看