android 自定义组合控件 顶部导航栏

Posted lenkevin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了android 自定义组合控件 顶部导航栏相关的知识,希望对你有一定的参考价值。

    在软件开发过程中,经常见到,就是APP 的标题栏样式几乎都是一样的,只是文字不同而已,两边图标不同。为了减少重复代码,提高效率, 方便大家使用,我们把标题栏通过组合的方式定义成一个控件。

例下图:                                                                                                  

技术分享

点击:

技术分享

 

如不设置左边,右边图片:

技术分享


下面说一下具体实现步骤:

步骤一:

导航栏包括:
* 返回按钮
* 标题
* 右侧按钮(功能不确定)

首先是布局文件,如下:

  1. </pre><p></p><pre name="code" class="java"><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="wrap_content"  
  5.     android:background="@android:color/holo_blue_light"  
  6.     tools:context=".MainActivity" >  
  7.   
  8.     <TextView  
  9.         android:id="@+id/text_title"  
  10.         android:layout_width="wrap_content"  
  11.         android:layout_height="wrap_content"  
  12.         android:layout_centerHorizontal="true"  
  13.         android:layout_centerVertical="true"  
  14.         android:textSize="25sp"  
  15.         android:gravity="center"  
  16.         android:textColor="@android:color/white"  
  17.         android:padding="2dp"  
  18.          />  
  19.   
  20.     <ImageView  
  21.         android:id="@+id/back_image"  
  22.         android:layout_width="40dp"  
  23.         android:layout_height="40dp"  
  24.         android:scaleType="centerInside"  
  25.         android:layout_alignParentLeft="true"  
  26.         android:layout_centerVertical="true"  
  27.         android:layout_marginLeft="12dp"  
  28.           />  
  29.   
  30.     <ImageView  
  31.         android:id="@+id/right_image"  
  32.         android:layout_width="40dp"  
  33.         android:layout_height="40dp"  
  34.         android:scaleType="centerInside"  
  35.         android:layout_alignParentRight="true"  
  36.         android:layout_centerVertical="true"  
  37.         android:layout_marginRight="12dp"  
  38.         />  
  39.   
  40. </RelativeLayout>  


步骤二:在values下新建 attrs文件 定义控件要用到的属性,如下面的代码所示。这里我们定义了标题栏文字(textText),字体大小(textSize),字体颜色(textColor),左边按钮 (leftBtn ),右边按钮 (rightBtn )  。(当然你还要以给它添加其它属性如背景)

 

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <declare-styleable name="Topbar">  
  4.         <attr name="titleText" format="string|reference" />  
  5.         <attr name="titleSize" format="dimension|reference" />  
  6.         <attr name="titleColor" format="color|reference" />  
  7.           
  8.         <attr name="leftBtn" format="reference"/>  
  9.         <attr name="rightBtn" format=" reference"/>  
  10.          
  11.     </declare-styleable>  
  12. </resources>  

步骤三:定义类Topbar继承自RelativeLayout,重写构造函数并构造方法中获得我们自定义的属性,具体代码如下。代码中定义了一个TextView显示标题文字,一个Imageview 显示左侧按钮,一个Imageview 显示右侧按钮 ,其他字段对应attrs中声明的属性。

 

 

  1. private ImageView backView;  
  2.    private ImageView rightView;  
  3.    private TextView titleView;  
  4.   
  5.    private String titleTextStr;   
  6.    private int titleTextSize ;  
  7.    private int  titleTextColor ;  
  8.   
  9.    private Drawable leftImage ;  
  10.    private Drawable rightImage ;  
  11.      
  12.    public TopBarView(Context context){  
  13.        this(context, null);  
  14.    }  
  15.   
  16.   
  17.    public TopBarView(Context context, AttributeSet attrs) {  
  18.        this(context, attrs,R.style.AppTheme);  
  19.          
  20.   
  21.    }  
  22.   
  23.    public TopBarView(Context context, AttributeSet attrs, int defStyle) {  
  24.     super(context, attrs, defStyle);  
  25.     getConfig(context, attrs);    
  26.        initView(context);  
  27. }  
  28.      
  29.    /**  
  30.     * 从xml中获取配置信息  
  31.     */   
  32.    private void getConfig(Context context, AttributeSet attrs) {  
  33.        //TypedArray是一个数组容器用于存放属性值    
  34.        TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.Topbar);    
  35.           
  36.        int count = ta.getIndexCount();  
  37.        for(int i = 0;i<count;i++)  
  38.        {  
  39.            int attr = ta.getIndex(i);    
  40.            switch (attr)    
  41.            {    
  42.            case R.styleable.Topbar_titleText:    
  43.             titleTextStr = ta.getString(R.styleable.Topbar_titleText);      
  44.                break;    
  45.            case R.styleable.Topbar_titleColor:    
  46.                // 默认颜色设置为黑色    
  47.             titleTextColor = ta.getColor(attr, Color.BLACK);    
  48.                break;    
  49.            case R.styleable.Topbar_titleSize:    
  50.                // 默认设置为16sp,TypeValue也可以把sp转化为px    
  51.                titleTextSize = ta.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(    
  52.                        TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics()));    
  53.                break;    
  54.    
  55.            case R.styleable.Topbar_leftBtn:    
  56.          
  57.             leftImage = ta.getDrawable(R.styleable.Topbar_leftBtn);    
  58.                break;   
  59.            case R.styleable.Topbar_rightBtn:    
  60.             rightImage = ta.getDrawable(R.styleable.Topbar_rightBtn);   
  61.                break;   
  62.            }   
  63.        }  
  64.   
  65.        //用完务必回收容器    
  66.        ta.recycle();   
  67.       
  68. }  
  69.   
  70.   
  71. private void initView(Context context)  
  72.    {  
  73.     View layout = LayoutInflater.from(context).inflate(R.layout.custom_groupwidget,   
  74.             this,true);  
  75.          
  76.        backView = (ImageView) layout.findViewById(R.id.back_image);  
  77.        titleView = (TextView) layout.findViewById(R.id.text_title);  
  78.        rightView = (ImageView) layout.findViewById(R.id.right_image);  
  79.        backView.setOnClickListener(this);  
  80.        rightView.setOnClickListener(this);  
  81.          
  82.        if(null != leftImage)  
  83.        backView.setImageDrawable(leftImage);  
  84.        if(null != rightImage)  
  85.        rightView.setImageDrawable(rightImage);  
  86.        if(null != titleTextStr)  
  87.        {  
  88.         titleView.setText(titleTextStr);  
  89.         titleView.setTextSize(titleTextSize);  
  90.         titleView.setTextColor(titleTextColor);  
  91.        }  
  92.    }  

步骤四:定义了一个OnClickListenner来监听ImageView的点击

 

 

  1.   private onTitleBarClickListener onMyClickListener;  
  2.      
  3.    /** 
  4.     * 设置按钮点击监听接口 
  5.     * @param callback 
  6.     */  
  7.    public void setClickListener(onTitleBarClickListener listener) {  
  8.        this.onMyClickListener = listener;  
  9.    }  
  10.   
  11.    /** 
  12.     * 导航栏点击监听接口 
  13.     */  
  14.    public static interface onTitleBarClickListener{  
  15.        /** 
  16.         * 点击返回按钮回调 
  17.         */  
  18.        void onBackClick();  
  19.   
  20.        void onRightClick();  
  21.    }  
  22.   
  23. @Override  
  24. public void onClick(View v) {  
  25.  int id = v.getId();  
  26.  switch(id)  
  27.  {  
  28.  case R.id.back_image:  
  29.      if(null != onMyClickListener)  
  30.      onMyClickListener.onBackClick();  
  31.      break;  
  32.  case R.id.right_image:  
  33.      if(null != onMyClickListener)  
  34.      onMyClickListener.onRightClick();  
  35.      break;  
  36.  }    
  37. }  

步骤五: 再看一下主布局怎样使用自定义控件:

 

 

  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     xmlns:custom="http://schemas.android.com/apk/res/com.example.customgroupwidget"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent"  
  6.     tools:context=".MainActivity" >  
  7.   
  8.     <com.example.customgroupwidget.TopBarView  
  9.         android:id="@+id/topbar"  
  10.         android:layout_width="wrap_content"  
  11.         android:layout_height="wrap_content"  
  12.         custom:titleText="我的消息"   
  13.         custom:titleSize="15sp"   
  14.         custom:titleColor="@android:color/white"   
  15.         custom:leftBtn="@drawable/back_page"   
  16.         custom:rightBtn="@drawable/edit_normal" />  
  17.   
  18. </RelativeLayout>  

步骤六:最后看一下Activity中的调用:

 

  1. public class MainActivity extends Activity implements onTitleBarClickListener {  
  2.   
  3.     private  TopBarView topbar;  
  4.     @Override  
  5.     protected void onCreate(Bundle savedInstanceState) {  
  6.         super.onCreate(savedInstanceState);  
  7.         setContentView(R.layout.activity_main);  
  8.           
  9.         topbar = (TopBarView)findViewById(R.id.topbar);  
  10.           
  11.         topbar.setClickListener(this);  
  12.     }  
  13.     @Override  
  14.     public void onBackClick() {  
  15.          Toast.makeText(MainActivity.this, "你点击了左侧按钮", Toast.LENGTH_LONG).show();  
  16.           
  17.     }  
  18.     @Override  
  19.     public void onRightClick() {  
  20.         Toast.makeText(MainActivity.this, "你点击了右侧按钮", Toast.LENGTH_SHORT).show();  
  21.           
  22.     }  
  23. }  

 demo下载

 

最后普及一下,attrs.xml中的属性的format(类型)说明

 

1. reference:参考某一资源ID。

    (1)属性定义:

            <declare-styleable name = "名称">

                   <attr name = "background" format = "reference" />

            </declare-styleable>

    (2)属性使用:

             <ImageView

                     android:layout_width = "42dip"
                     android:layout_height = "42dip"
                     android:background = "@drawable/图片ID"

                     />

2. color:颜色值。

    (1)属性定义:

            <declare-styleable name = "名称">

                   <attr name = "textColor" format = "color" />

            </declare-styleable>

    (2)属性使用:

            <TextView

                     android:layout_width = "42dip"
                     android:layout_height = "42dip"
                     android:textColor = "#00FF00"

                     />

3. boolean:布尔值。

    (1)属性定义:

            <declare-styleable name = "名称">

                   <attr name = "focusable" format = "boolean" />

            </declare-styleable>

    (2)属性使用:

            <Button

                    android:layout_width = "42dip"
                    android:layout_height = "42dip"

                    android:focusable = "true"

                    />

4. dimension:尺寸值。

    (1)属性定义:

            <declare-styleable name = "名称">

                   <attr name = "layout_width" format = "dimension" />

            </declare-styleable>

    (2)属性使用:

            <Button

                    android:layout_width = "42dip"
                    android:layout_height = "42dip"

                    />

5. float:浮点值。

    (1)属性定义:

            <declare-styleable name = "AlphaAnimation">

                   <attr name = "fromAlpha" format = "float" />
                   <attr name = "toAlpha" format = "float" />

            </declare-styleable>

    (2)属性使用:

            <alpha
                   android:fromAlpha = "1.0"
                   android:toAlpha = "0.7"

                   />

6. integer:整型值。

    (1)属性定义:

            <declare-styleable name = "AnimatedRotateDrawable">

                   <attr name = "visible" />
                   <attr name = "frameDuration" format="integer" />
                   <attr name = "framesCount" format="integer" />
                   <attr name = "pivotX" />
                   <attr name = "pivotY" />
                   <attr name = "drawable" />

            </declare-styleable>

    (2)属性使用:

            <animated-rotate

                   xmlns:android = "http://schemas.android.com/apk/res/android
                   android:drawable = "@drawable/图片ID" 
                   android:pivotX = "50%" 
                   android:pivotY = "50%" 
                   android:framesCount = "12" 
                   android:frameDuration = "100"

                   />

7. string:字符串。

    (1)属性定义:

            <declare-styleable name = "MapView">
                   <attr name = "apiKey" format = "string" />
            </declare-styleable>

    (2)属性使用:

            <com.google.android.maps.MapView
                    android:layout_width = "fill_parent"
                    android:layout_height = "fill_parent"
                    android:apiKey = "0jOkQ80oD1JL9C6HAja99uGXCRiS2CGjKO_bc_g"

                    />

8. fraction:百分数。

    (1)属性定义:

            <declare-styleable name="RotateDrawable">
                   <attr name = "visible" />
                   <attr name = "fromDegrees" format = "float" />
                   <attr name = "toDegrees" format = "float" />
                   <attr name = "pivotX" format = "fraction" />
                   <attr name = "pivotY" format = "fraction" />
                   <attr name = "drawable" />
            </declare-styleable>

    (2)属性使用:

            <rotate

                   xmlns:android = "http://schemas.android.com/apk/res/android"
               android:interpolator = "@anim/动画ID"

                   android:fromDegrees = "0"
               android:toDegrees = "360"

                   android:pivotX = "200%"

                   android:pivotY = "300%"
               android:duration = "5000"

                   android:repeatMode = "restart"

                   android:repeatCount = "infinite"

                   />

9. enum:枚举值。

    (1)属性定义:

            <declare-styleable name="名称">
                   <attr name="orientation">
                          <enum name="horizontal" value="0" />
                          <enum name="vertical" value="1" />
                   </attr>           

            </declare-styleable>

    (2)属性使用:

            <LinearLayout

                    xmlns:android = "http://schemas.android.com/apk/res/android"
                    android:orientation = "vertical"
                    android:layout_width = "fill_parent"
                    android:layout_height = "fill_parent"
                    >
            </LinearLayout>

10. flag:位或运算。

     (1)属性定义:

             <declare-styleable name="名称">
                    <attr name="windowSoftInputMode">
                            <flag name = "stateUnspecified" value = "0" />
                            <flag name = "stateUnchanged" value = "1" />
                            <flag name = "stateHidden" value = "2" />
                            <flag name = "stateAlwaysHidden" value = "3" />
                            <flag name = "stateVisible" value = "4" />
                            <flag name = "stateAlwaysVisible" value = "5" />
                            <flag name = "adjustUnspecified" value = "0x00" />
                            <flag name = "adjustResize" value = "0x10" />
                            <flag name = "adjustPan" value = "0x20" />
                            <flag name = "adjustNothing" value = "0x30" />
                     </attr>        

             </declare-styleable>

     (2)属性使用:

            <activity

                   android:name = ".StyleAndThemeActivity"
                   android:label = "@string/app_name"
                   android:windowSoftInputMode = "stateUnspecified | stateUnchanged | stateHidden">
                   <intent-filter>
                          <action android:name = "android.intent.action.MAIN" />
                          <category android:name = "android.intent.category.LAUNCHER" />
                   </intent-filter>
             </activity>

特别要注意:

     属性定义时可以指定多种类型值。

    (1)属性定义:

            <declare-styleable name = "名称">

                   <attr name = "background" format = "reference|color" />

            </declare-styleable>

    (2)属性使用:

             <ImageView

                     android:layout_width = "42dip"
                     android:layout_height = "42dip"
                     android:background = "@drawable/图片ID|#00FF00"

                     />

 

以上是关于android 自定义组合控件 顶部导航栏的主要内容,如果未能解决你的问题,请参考以下文章

Android自定义View的三种实现方式

《移动项目实践》实验报告——Android组合控件

《移动项目实践》实验报告——Android组合控件

Android 自定义View 三板斧之一——组合现有控件

上位机学习记录组合控件的应用(控件堆叠+重置)与UI导航栏的编写

Android 手机卫士--自定义组合控件构件布局结构