关于自定义标题栏的实现

本文详细介绍了如何实现自定义标题栏,包括编写布局文件、创建自定义控件、设置按钮点击效果、使用PopupWindow及弹窗背景边框等步骤,并提供了相关教程链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


步骤

1、编写布局文件layout_topbar.xml,使用相对布局,左边一个button,跟父控件左对齐后外边距为5dp,右边的button也是一样,中间的标题居中显示 。

ncoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/leftButton"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="5dp" />

    <TextView
        android:id="@+id/titleText"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:paddingTop="6dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:gravity="center" />

    <Button
        android:id="@+id/rightButton"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginRight="5dp" />
</RelativeLayout>

2.编写自定义控件,继承RelativeLayout,获取自定义属性并给对应的控件赋值 。

package com.example.ddf;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;



/**
 * 描述:自定义topbar的实现
 * <p>
 * Created by djj on 2016/12/23.
 */

public class TopBar extends RelativeLayout {

    private Button leftButton, rightButton;
    private TextView titleTextView;
    private OnLeftAndRightClickListener listener;//监听点击事件

    //设置监听器
    public void setOnLeftAndRightClickListener(OnLeftAndRightClickListener listener) {
        this.listener = listener;
    }

    //按钮点击接口
    public interface OnLeftAndRightClickListener {
        void OnLeftButtonClick();

        void OnRightButtonClick();
    }
    //设置左边按钮的可见性
    public void setLeftButtonVisibility(boolean flag){
        if (flag)
            leftButton.setVisibility(View.VISIBLE);
        else
            leftButton.setVisibility(View.GONE);
    }

    //设置右边按钮的可见性
    public void setRightButtonVisibility(boolean flag){
        if (flag)
            rightButton.setVisibility(View.VISIBLE);
        else
            rightButton.setVisibility(View.GONE);
    }
    public TopBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.laout_topbar, this);
        leftButton = (Button) findViewById(R.id.leftButton);
        rightButton = (Button) findViewById(R.id.rightButton);
        titleTextView = (TextView) findViewById(R.id.titleText);
        leftButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    listener.OnLeftButtonClick();//点击回调
                }
            }
        });
        rightButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    listener.OnRightButtonClick();//点击回调
                }
            }
        });

        //获得自定义属性并赋值
        TypedArray typeArray = context.obtainStyledAttributes(attrs, R.styleable.TopBar);
        int leftBtnBackground = typeArray.getResourceId(R.styleable.TopBar_leftBackground, 0);
        int rightBtnBackground = typeArray.getResourceId(R.styleable.TopBar_rightBackground, 0);
        String titleText = typeArray.getString(R.styleable.TopBar_titleText);
        float titleTextSize = typeArray.getDimension(R.styleable.TopBar_titleTextSize, 18);
        int titleTextColor = typeArray.getColor(R.styleable.TopBar_titleTextColor, 0x38ad5a);
        //释放资源
        typeArray.recycle();
        leftButton.setBackgroundResource(leftBtnBackground);
        rightButton.setBackgroundResource(rightBtnBackground);
        titleTextView.setText(titleText);
        titleTextView.setTextSize(titleTextSize);
        titleTextView.setTextColor(titleTextColor);
    }
}

3、调用自定义控件,在需要的activity或fragment的xml布局中调用

    <com.example.ddf.TopBar
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/topbar"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginBottom="20dp"
        android:background="@drawable/biaotibeijing"
        app:leftBackground="@layout/left_button_selector"
        app:rightBackground="@layout/right_button_selector"
        app:titleText="添加美食"
        app:titleTextColor="#FFF"
        app:titleTextSize="15dp" />

4.左、右按钮点击变色的设置,右边按钮一样,这里省略

right_button_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/rightpress" android:state_pressed="true"/>
    <item android:drawable="@drawable/rightnormal" />
</selector>

left_button_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/backpress" android:state_pressed="true"/>
    <item android:drawable="@drawable/backnormal" />
</selector>

5.最后在activity或fragment中去实现其功能。

代码如下:

TopBar topBar = (TopBar) findViewById(R.id.topbar);
        topBar.setOnLeftAndRightClickListener(new TopBar.OnLeftAndRightClickListener() {
            @Override
            public void OnLeftButtonClick() {
                finish();//左边按钮实现的功能逻辑
            }

            @Override
            public void OnRightButtonClick() {
//右边按钮实现的功能逻辑
                Toast.makeText(HomeActivity.this, "RightButton", Toast.LENGTH_SHORT).show();
            }
        });


6.设置弹窗设置利用popupwindow

popup_window.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@layout/pop_window_bg">

    <ListView
        android:id="@+id/lsvMore"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:divider="#a51919"
        android:layout_weight="1" 
        android:dividerHeight="2dp"/>

</LinearLayout>

7.设置弹窗背景边框

popup_window_bg.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- dashWidth指的是边线的长度 dashGap 指的是每条线之间的间距 width指的是边线的宽度 -->
    <stroke
        android:width="2dp"
        android:color="#a51919"
        android:dashGap="2dp"
        android:dashWidth="10dp" />

    <corners
        android:bottomLeftRadius="2dp"
        android:bottomRightRadius="2dp"
        android:topLeftRadius="2dp"
        android:topRightRadius="2dp" />

</shape>

8.在avitvity中引用弹窗设置

AddActivity.java

public void initpopupwindow()
	{
		 // TODO: 2016/5/17 设置该Activity使用的布局文件
        btnPopup = (Button) findViewById(R.id.rightButton);// TODO: 2016/5/17 获取弹出按钮控件
        // TODO: 2016/5/17 给按钮设置单击事件监听
        btnPopup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO: 2016/5/17 构建一个popupwindow的布局
                View popupView = AddFoodActivity.this.getLayoutInflater().inflate(R.layout.popup_window, null);

                // TODO: 2016/5/17 为了演示效果,简单的设置了一些数据,实际中大家自己设置数据即可,相信大家都会。
                ListView lsvMore = (ListView) popupView.findViewById(R.id.lsvMore);
                lsvMore.setAdapter(new ArrayAdapter<String>(AddFoodActivity.this, android.R.layout.simple_list_item_1, datas));

                lsvMore.setOnItemClickListener(new AdapterView.OnItemClickListener() {
				  
				    public void onItemClick(AdapterView<?>arg0,View arg1,int arg2,long arg3)
				    {
				    	switch(arg2)
				    	{case 0: 
				    		Intent intent=new Intent(AddFoodActivity.this,MakeAudioActivity.class);
						    startActivity(intent);
						    break;
				    	case 1:
				    		Intent intent2=new Intent(AddFoodActivity.this,MakeVideoActivity.class);
							startActivity(intent2);
						break;
						default:break;
				    	}
				    }
                });
                // TODO: 2016/5/17 创建PopupWindow对象,指定宽度和高度
                PopupWindow window = new PopupWindow(popupView, 150, 150);
                // TODO: 2016/5/17 设置动画
                window.setAnimationStyle(R.style.popup_window_anim);
                // TODO: 2016/5/17 设置背景颜色
                window.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#F8F8F8")));
                // TODO: 2016/5/17 设置可以获取焦点
                window.setFocusable(true);
                // TODO: 2016/5/17 设置可以触摸弹出框以外的区域
                window.setOutsideTouchable(true);
                // TODO:更新popupwindow的状态
                window.update();
                // TODO: 2016/5/17 以下拉的方式显示,并且可以设置显示的位置
                window.showAsDropDown(btnPopup, 0, 10);
            }
        });
	}




参考网址:

自定义标题栏:https://www.jianshu.com/p/0763114e7738

弹窗:https://blog.youkuaiyun.com/csdnzouqi/article/details/51433633



最后在activity或fragment中去实现其功能。
自定义winform 窗口标题栏 主要代码 public partial class ZForm : Form { private bool moving = false; private Point oldMousePosition; public new FormBorderStyle FormBorderStyle { get { return base.FormBorderStyle; } set { if (value != FormBorderStyle.Sizable && value != FormBorderStyle.SizableToolWindow) { titlepanel.Controls.Remove(button2); } base.FormBorderStyle = value; } } #region 隐藏父类的属性,使其不可见 [Browsable(false)] public new string Text { get { return titlelabel.Text; } set { } } [Browsable(false)] public new bool ControlBox { get { return false; } set { base.ControlBox = false; } } #endregion [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] [Description("窗体标题")] public string Title { get { return titlelabel.Text; } set { titlelabel.Text = value; } } [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] [Description("窗体标题字体样式")] public Font TitleFont { get { return titlelabel.Font; } set { titlelabel.Font = value; } } [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] [Description("窗体标题字体颜色")] public Color TitleColor { get { return titlelabel.ForeColor; } set { titlelabel.ForeColor = value; } } [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] [Description("窗体标题栏背景色")] public Color TitleBarBackColor { get { return titlepanel.BackColor; } set { titlepanel.BackColor = value; } } public new bool MaximizeBox { get { return titlepanel.Contains(button2); } set { if (!value) { titlepanel.Controls.Remove(button2); } else if (!titlepanel.Contains(button2)) { titlepanel.Controls.Add(button2); } } } public new bool MinimizeBox { get { return titlepanel.Contains(button3); } set { if (!value) { titlepanel.Controls.Remove(button3); } else if (!titlepanel.Contains(button3)) { titlepanel.Controls.Add(button3); } } } private void ResetTitlePanel() { base.ControlBox = false; base.Text = null; SetToolTip(button1, "关闭"); button2.Size = button1.Size; SetToolTip(button2, "最大化或还原"); button3.Size = button1.Size; SetToolTip(button3, "最小化"); } private void SetToolTip(Control ctrl, string tip) { new ToolTip().SetToolTip(ctrl, tip); } public ZForm() { InitializeComponent(); ResetTitlePanel(); } private void Titlebutton_Click(object sender, EventArgs e) { Button btn = (Button)sender; switch (btn.Tag.ToString()) { case "close": { this.Close(); break; } case "max": { if (this.WindowState == FormWindowState.Maximized) { this.WindowState = FormWindowState.Normal; } else { this.WindowState = FormWindowState.Maximized; } break; } case "min": { if (this.WindowState != FormWindowState.Minimized) { this.WindowState = FormWindowState.Minimized; } break; } } } private void Titlepanel_MouseDown(object sender, MouseEventArgs e) { if (this.WindowState == FormWindowState.Maximized) { return; } //Titlepanel.Cursor = Cursors.NoMove2D; oldMousePosition = e.Location; moving = true; } private void Titlepanel_MouseUp(object sender, MouseEventArgs e) { //Titlepanel.Cursor = Cursors.Default; moving = false; } private void Titlepanel_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left && moving) { Point newPosition = new Point(e.Location.X - oldMousePosition.X, e.Location.Y - oldMousePosition.Y); this.Location += new Size(newPosition); } } private void Titlepanel_DoubleClick(object sender, EventArgs e) { if (titlepanel.Contains(button2)) { button2.PerformClick(); } } private void titlepanel_ControlRemoved(object sender, ControlEventArgs e) { switch (e.Control.Name) { case "button2": { if (titlepanel.Contains(button3)) { button3.Left = button1.Left - button1.Width; } break; } } } private void titlepanel_ControlAdded(object sender, ControlEventArgs e) { switch (e.Control.Name) { case "button2": { if (titlepanel.Contains(button3)) { button3.Left = button2.Left - button2.Width; } break; } case "button3": { if (titlepanel.Contains(button2)) { button3.Left = button2.Left - button2.Width; } break; } } } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值