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>
  • 相关阅读:
    jquery处理鼠标左中右键事件
    bootstrap弹出框
    移动端去掉a标签点击时出现的背景
    sessionStorage
    页面滑动到最下面,执行代码
    判断页面时向上滚动还是向下滚动
    sql 时间查询 /sql中判断更新或者插入/查询一年所有双休日
    求取最大值
    Repeater 获取数据值
    加载完毕后执行计算
  • 原文地址:https://www.cnblogs.com/alexkn/p/5456927.html
Copyright © 2011-2022 走看看