Android custom title TitleView, androidtitleview

Source: Internet
Author: User

Android custom title TitleView, androidtitleview

During Android development, we often encounter a project that needs to repeatedly define the title bar of the same style. Android has successively launched actionBar and toolBar. I believe that useful friends will also encounter some unsatisfactory times, for example, when the title bar is in the upper-right corner, you need to customize the xml file to the toolBar. If you do not know the actionBar, you can find the corresponding articles for the toolBar, here we will introduce how custom titleBar meets the requirements of domestic theme styles.

To see the effect in advance, first:

Preparations 

1. pre-defined id for the title bar titleView, in ids. xml under values

 1 <?xml version="1.0" encoding="utf-8"?> 2 <resources> 3  4     <item name="tv_title_name" type="id"/> 5     <item name="tv_left_text" type="id"/> 6     <item name="iv_left_image" type="id"/> 7     <item name="iv_right_image" type="id"/> 8     <item name="iv_right_image_two" type="id"/> 9     <item name="tv_right_text" type="id"/>10     <item name="tv_right_text_two" type="id"/>11 12 </resources>

The left-side return button id, title id, and back-side button id are defined. There are two options on the left: ImageView and TextView. Two buttons can exist on the right at the same time, image button and text button combination.

2. Customize the title bar attributes in attr. xml under valuse

1 <? Xml version = "1.0" encoding = "UTF-8"?> 2 <resources> 3 <! -- Title attribute --> 4 <declare-styleable name = "TitleAttr"> 5 <attr name = "title_name" format = "reference | string"/> 6 <attr name = "title_text_color "format =" reference | color "/> 7 <attr name =" title_drawable_right "format =" reference "/> 8 <attr name =" title_drawable_left "format =" reference "/> 9 <attr name = "title_text_size" format = "reference | dimension"/> 10 <attr name = "left_text" format = "reference | string"/> 11 <attr name =" left_image "format =" reference "/> 12 <attr name =" small_text_size "format =" reference | dimension "/> 13 <attr name =" title_gravity "> 14 <enum name = "left" value = "3"/> 15 <enum name = "center" value = "17"/> 16 <enum name = "right" value = "5"/> 17 </attr> 18 <attr name = "right_image" format = "reference"/> 19 <attr name = "right_text" format = "reference | string"/> 20 <attr name = "right_image_two" format = "reference"/> 21 <attr name = "right_text_two" format = "reference | string"/> 22 <attr name = "title_height" format =" dimension "/> 23 <attr name =" right_text_drawable_right "format =" reference "/> 24 <attr name =" right_text_drawable_left "format =" reference "/> 25 <attr name =" right_text_two_drawable_right "format =" reference "/> 26 <attr name =" relative "format =" reference "/> 27 <attr name =" left_text_drawable_right "format =" reference "/> 28 <attr name = "left_text_drawable_left" format = "reference"/> 29 </declare-styleable> 30 </resources>
  • Coding implementation
  • With the above preparations, we can start coding now. Here we will first look at how to introduce our custom controls in xml:
    1 <com. jarek. library. titleView 2 android: id = "@ + id/title_main" 3 android: layout_width = "match_parent" 4 android: background = "# 0093fe" 5 title: title_name = "title" 6 title: right_text = "@ string/more" 7 title: title_text_color = "@ android: color/white" 8 title: right_image_two = "@ mipmap/icon_crop_rotate" 9 title: title_text_size = "20sp" 10 title: small_text_size = "15sp" 11 title: left_text = "return" 12 title: left_text_drawable_left = "@ mipmap/back_normal" 13 title: right_text_drawable_right = "@ mipmap/bar_button_right" 14 android: layout_height = "50dp"/>

    Here, the title label is our custom. First, we create a class that inherits from RelativeLayout. Here, we select RelativeLayout as the parent class container, so that RelativeLayout can easily control relative positions.
    First, we need to obtain the TypedArray object, through which the values of all custom attributes are obtained:

    TypedArray typeArray = context.obtainStyledAttributes(attrs,     R.styleable.TitleAttr);

    After obtaining the typedArray object, you can add the button to the container. First, check the first return button on the left. If you add the button, check the code first:

     int leftText =  typeArray.getResourceId(R.styleable.TitleAttr_left_text, 0);  CharSequence charSequence =  leftText > 0 ? typeArray.getResources().getText(leftText) : typeArray.getString(R.styleable.TitleAttr_left_text);

    Here, left_text is a custom attribute, indicating the text displayed in the TextView on the left. The text can be a predefined string in the Application resource file, or you can enter the text directly. After obtaining the corresponding styleable, first, judge whether it is greater than 0. If it is greater than 0, it indicates that it is defined in string. getResources (). getText () is used to obtain the value. If it is equal to 0, it indicates that the value may be assigned directly. How do I assign a value to TextView after obtaining the value? Here, we need to give it width and height first, which is required by all controls.

    /** * layout params of RelativeLayout * @return LayoutParams */private LayoutParams initLayoutParams () {        return new LayoutParams(LayoutParams.WRAP_CONTENT,   LayoutParams.MATCH_PARENT);    }

    Let's write a method separately, and then we can directly use

    LayoutParams params = initLayoutParams();

    To get the preset width and high value. here we can see that the height is filled with the parent control, and the width is adaptive. Then there is a new TextView:

    /**     * create TextView     * @param context Context     * @param id the id of TextView     * @param charSequence text to show     * @param params relative params     * @return the TextView which is inited     */    @NonNull    private TextView createTextView(Context context, int id, CharSequence charSequence, LayoutParams params) {        TextView textView = new TextView(context);        textView.setLayoutParams(params);        textView.setGravity(Gravity.CENTER);        textView.setId(id);        textView.setMinWidth((int)getPixelSizeByDp(minViewWidth));        textView.setText(charSequence);        return textView;    }

    Here we can see that we have passed in the default id value, the content to be displayed, and the preceding LayoutParams. After creating a TextView, you can also set the Drawable of TextView. You can set it through the Custom Attributes left_text_drawable_right and left_text_drawable_left. Here the left and right are set, and the upper and lower correspond to the following settings:

        /**     * drawable of TextView     * @param typeArray TypedArray     * @param leftDrawableStyleable leftDrawableStyleable     * @param rightDrawableStyleable rightDrawableStyleable     * @param textView which TextView to set     */    private void setTextViewDrawable(TypedArray typeArray, int leftDrawableStyleable, int rightDrawableStyleable, TextView textView) {        int leftDrawable = typeArray.getResourceId(leftDrawableStyleable, 0);        int rightDrawable = typeArray.getResourceId(rightDrawableStyleable, 0);        textView.setCompoundDrawablePadding((int)getPixelSizeByDp(drawablePadding));        textView.setCompoundDrawablesWithIntrinsicBounds(leftDrawable, 0, rightDrawable, 0);    }

    Here we also extract a method, and then use:

    setTextViewDrawable(typeArray, R.styleable.TitleAttr_left_text_drawable_left, R.styleable.TitleAttr_left_text_drawable_right, mLeftBackTextTv);

    You can set drawable for the specified TextView. After creating a TextView, we mentioned previously that we use a relative layout. We need to specify location rules:

    params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);

    It is displayed on the left. You can also set the font size by customizing the attributes small_text_size (Text Size on both sides) and title_text_size (Title text size:

        /**     * get the dimension pixel size from typeArray which is defined in attr     * @param typeArray TypedArray     * @param stylable stylable     * @param defaultSize defaultSize     * @return the dimension pixel size     */    private float getDimensionPixelSize(TypedArray typeArray, int stylable, int defaultSize) {        int sizeStyleable = typeArray.getResourceId(stylable, 0);        return sizeStyleable > 0 ? typeArray.getResources().getDimensionPixelSize(sizeStyleable) : typeArray.getDimensionPixelSize(stylable, (int)getPiselSizeBySp(defaultSize));    }

    Similarly, here we also write a separate method to do this. The usage of TypedArray is not described much. You can refer to other articles for more information. Set the font size as follows:

         float textSize = getDimensionPixelSize(typeArray, R.styleable.TitleAttr_small_text_size, defaultSmallTextSize);        mLeftBackTextTv.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);

    Text color, the same principle:

        /**     * get textColor     * @param typeArray TypedArray     * @return textColor     */    private int getTextColorFromAttr (TypedArray typeArray) {        int textColorStyleable = typeArray.getResourceId(R.styleable.TitleAttr_title_text_color, 0);        if (textColorStyleable > 0) {            return typeArray.getResources().getColor(textColorStyleable);        } else {            return typeArray.getColor(R.styleable.TitleAttr_title_text_color, textColor);        }    }

    Then call the method to set the color:

    mLeftBackTextTv.setTextColor(getTextColorFromAttr(typeArray));

    So far, the first text button on the left side. Or the text button with an image is created, and the last step is worse:

    mLeftBackTextTv.setTextColor(getTextColorFromAttr(typeArray));

    Other buttons, in the same way, can be added to the container in sequence, so we will not talk about it more. The titleView we need has been created so far, and can be called directly in the future, coding does not need to be repeated in each place

Project address: github source code download

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.