自定义(标题栏)TitleBar样式

这段时间比较闲,整理了下自己以前的自定义标题栏,比较简单,如有更好的写法,欢迎批评指教。
样式如下:


1.布局文件




  
    

    

    

    

    


 

2.自定义代码

/**
 * @author J.query
 * @date 2016/5/24
 * @email [email protected]
 */
public class TopTitleBar extends LinearLayout {

    private TextView mLeftTv;
    private TextView mRightTv;
    private ImageView mRightImg;

    public TopTitleBar(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.include_title, this, true);

        TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.Top_title);

        boolean mShowLeft = a.getBoolean(R.styleable.Top_title_showLeft, true);
        mLeftTv = (TextView) findViewById(R.id.tv_back);
        if (!mShowLeft) {
            mLeftTv.setVisibility(GONE);
        }

        String rightStr = a.getString(R.styleable.Top_title_rightTitle);
        mRightTv = (TextView) findViewById(R.id.tv_right);
        if (rightStr != null) {
            mRightTv.setText(rightStr);
        }

        String mTitle = a.getString(R.styleable.Top_title_title);
        TextView mTvTitle = (TextView) findViewById(R.id.include_tv);
        if (mTitle != null) {
            mTvTitle.setText(mTitle);
        }

        int mResourceId = a.getResourceId(R.styleable.Top_title_rightRes, -1);
        mRightImg = (ImageView) findViewById(R.id.img_right);
        if (mResourceId != -1) {
            mRightImg.setVisibility(VISIBLE);
            mRightImg.setImageResource(mResourceId);
        }

        a.recycle();
    }

    public void setLeftVisible(boolean b) {
        if (mLeftTv != null)
            mLeftTv.setVisibility(b ? VISIBLE : GONE);
    }

    public void setRightTvVisible(boolean b) {
        if (mRightTv != null)
            mRightTv.setVisibility(b ? VISIBLE : GONE);
    }

    public void setRightVisible(boolean b) {
        if (mRightImg != null)
            mRightImg.setVisibility(b ? VISIBLE : GONE);
    }
}


3. attrs.xml  文件



    
        
        
        
        
    






4.使用方式

布局文件使用示例:
<.......widgets.TopTitleBar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:title="标题" />

Activity使用示例:

我是把他集成到BaseActivity里面的,避免重复的写返回键

  public void setTitle(String title) {
        TextView tvTitle = (TextView) findViewById(R.id.include_tv);
        tvTitle.setText(title);
        findViewById(R.id.tv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

你可能感兴趣的:(自定义)