结合Toolbar自定义状态栏

首先看图:

你没有看错,这是结合toolbar做出来的!

下面说说如何实现:

一、布局




    

        

    

有人会问为何能使用toolbar去包裹一个view,答案是因为toolbar是继承viewGroup,so!

下面是自定义的一些属性:



    
        
        
    

二、代码


import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.ColorInt;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.clang.merchant.manage.main.R;

/**
 * @Author: wliang.
 * @Date: 2016/4/25 16:25
 * @E-mail: [email protected]
 */
public class TitleView extends RelativeLayout {

    private TextView mTitle;
    private Toolbar mToolBar;

    public TitleView(Context context) {
        this(context, null);
    }

    public TitleView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TitleView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.TitleView);

        String titleText = typedArray.getString(R.styleable.TitleView_title_text);
        int backgroundColor = typedArray.getColor(R.styleable.TitleView_background_color , ContextCompat.getColor(getContext(), R.color.colorPrimary));

        View view = inflate(context, R.layout.title_view_layout, this);

        mToolBar = (Toolbar) view.findViewById(R.id.titleViewToolBar);
        mTitle = (TextView) view.findViewById(R.id.titleViewText);
        mToolBar.setTitle("");

        if (!TextUtils.isEmpty(titleText)){
            mTitle.setText(titleText);
        }

        mToolBar.setBackgroundColor(backgroundColor);

        typedArray.recycle();
    }


    public Toolbar getToolBar() {
        return mToolBar;
    }

    public void setTitle(@Nullable String titleText) {
        mTitle.setText(Html.fromHtml(titleText));
    }


    public void setBackgroundColor(@ColorInt int color){
        mToolBar.setBackgroundColor(color);
    }
}

三、使用方法

  
 TitleView mTitleView = (TitleView) findViewById(R.id.orderInfoTitleView);

 if (mTitleView != null) {
    setSupportActionBar(mTitleView.getToolBar());
 }
 getSupportActionBar().setDisplayHomeAsUpEnabled(true);

 

转载于:https://my.oschina.net/wvliang/blog/694403

你可能感兴趣的:(结合Toolbar自定义状态栏)