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>
  • 相关阅读:
    solr6.0学习
    shell定时任务
    LINUX调优
    OnlineJudge大集合
    [GRYZ2015]快排练习
    [洛谷1240]诸侯安置
    [NOI导刊2011]影像之结构化特征
    手把手教你写对拍程序(PASCAL)
    [NOIP2013]转圈游戏
    [GRYZ2015]阿Q的停车场
  • 原文地址:https://www.cnblogs.com/alexkn/p/5456927.html
Copyright © 2011-2022 走看看