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>
  • 相关阅读:
    继续Delphi调用Wcf
    我用 Windows Live Writer 写随笔
    "WCF 服务编程"刚到,第一印象,内纸张很差
    我的asp.net网站小项目,体现了我学习的几个阶段,现在学习到WCF阶段
    菜单设计
    求圆的面积
    dataGridView 批量更新
    Android简单实现对话框
    dephi 程序输入法中英文自动切换实现
    Delphi捕捉DLL执行所抛出的异常。(转)
  • 原文地址:https://www.cnblogs.com/alexkn/p/5456927.html
Copyright © 2011-2022 走看看