Android通用控件及响应

在Android的开发中,可能需要有一些自定义的Layout,比如APP中常常需要一个通用的title。但是Android自带的可能并不能满足要求,需要自己实现,但是因为一个APP中常常含有多个Activity,这个时候为了提高复用性,常常自己定义一个CommonTitle。本文自己实现了一个CommonTitle。

  1. 新建一个布局

    1
    2
    3
    
    <!--?xml version="1.0" encoding="utf-8"?-->
    <button>
    </button>
    
  2. 新建一个CommonTitle类,继承LinearLayout

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    
    package com.example.uicustomviews;
    
    import android.app.Activity;
    import android.content.Context;
    import android.util.AttributeSet;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.widget.Button;
    import android.widget.LinearLayout;
    import android.widget.Toast;
    
    public class CommonTitle extends LinearLayout {
        public CommonTitle(Context context, AttributeSet attrs) {
            super(context, attrs);
            LayoutInflater.from(context).inflate(R.layout.commontitle, this);
    
            Button backButton = (Button)findViewById(R.id.backButton);
            backButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    // TODO Auto-generated method stub
                    ((Activity)getContext()).finish();
                }
            });
    
            Button editButton = (Button)findViewById(R.id.editButton);
            editButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    // TODO Auto-generated method stub
                    Toast.makeText(getContext(), "Please edit the context", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
    
  3. 在需要的Activity中引入自己定义的CommonTitle即可

    1
    
    <!-- Your Activity layout XML -->
    

运行效果如下:
QQ截图20150831220854