Android 自定义标题栏:使用 ViewGroup 创建 TitleView
Android 中,我们可以通过继承 ViewGroup 类来自定义 TitleView,实现自己想要的标题栏效果。
首先,我们需要在自定义 ViewGroup 中添加自己想要的子 View,例如左侧返回按钮、中间标题文字、右侧菜单按钮等。
在 onLayout() 方法中,我们需要对子 View 进行布局,根据自己的设计要求来设置子 View 的位置和大小。
在 onMeasure() 方法中,我们需要测量子 View 的大小,使得它们能够正确地显示在标题栏中。
最后,在 onDraw() 方法中,我们可以对标题栏进行绘制,添加背景、分割线等效果。
具体实现代码如下所示:
public class TitleView extends ViewGroup {
private View mLeftView;
private View mTitleView;
private View mRightView;
public TitleView(Context context) {
super(context);
init();
}
public TitleView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
// 添加子 View
mLeftView = new ImageView(getContext());
mLeftView.setImageResource(R.drawable.ic_back);
addView(mLeftView);
mTitleView = new TextView(getContext());
((TextView) mTitleView).setText('Title');
addView(mTitleView);
mRightView = new ImageView(getContext());
mRightView.setImageResource(R.drawable.ic_menu);
addView(mRightView);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 测量子 View 的大小
measureChild(mLeftView, widthMeasureSpec, heightMeasureSpec);
measureChild(mTitleView, widthMeasureSpec, heightMeasureSpec);
measureChild(mRightView, widthMeasureSpec, heightMeasureSpec);
// 设置自身大小
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(width, height);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// 布局子 View
int left = 0;
int top = 0;
int right = mLeftView.getMeasuredWidth();
int bottom = mLeftView.getMeasuredHeight();
mLeftView.layout(left, top, right, bottom);
left = (getWidth() - mTitleView.getMeasuredWidth()) / 2;
top = 0;
right = left + mTitleView.getMeasuredWidth();
bottom = mTitleView.getMeasuredHeight();
mTitleView.layout(left, top, right, bottom);
left = getWidth() - mRightView.getMeasuredWidth();
top = 0;
right = getWidth();
bottom = mRightView.getMeasuredHeight();
mRightView.layout(left, top, right, bottom);
}
@Override
protected void onDraw(Canvas canvas) {
// 绘制背景和分割线
super.onDraw(canvas);
Paint paint = new Paint();
paint.setColor(Color.GRAY);
canvas.drawLine(0, getHeight() - 1, getWidth(), getHeight() - 1, paint);
}
}
使用自定义 TitleView 时,只需要在布局文件中添加 TitleView 即可:
<com.example.myapplication.TitleView
android:layout_width="match_parent"
android:layout_height="wrap_content" />
然后就可以在代码中对 TitleView 进行操作,比如设置标题文字和点击事件等。
原文地址: https://www.cveoy.top/t/topic/n7vJ 著作权归作者所有。请勿转载和采集!