安卓(Android) 自定义控件 导航栏(TopBar)

  • 作为一只安卓自学的小白,今天第一天发表微博还是有点小激动的,好了,废话少说下面开始我的安卓自定义控件知识总结。我的demo是一个自定义的TopBar,左边一个Button按钮,中间是一个标题,右边也是一个Button按钮。在安卓开发中自定义控件的技术是一个项目中不可缺少的一部分,下面我就用我的小demo一步步详细介绍,麻雀虽小五脏俱全,相信看完这篇文章对自定义控件肯定会有一个很好的掌握。

    首先来看一下我的demo的效果图:
    这里写图片描述

    安卓自定义控件基本可以分为三大步骤:

  • 1、在xml文件中设计控件需要的属性

  • 2、定义一个类获取xml的属性实现View

  • 3、引用自定义View

1.在xml文件中设计控件需要的属性

首先在res/values目录下新建一个xml文件atts.xml。代码如下

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="TopBar">
        <attr name="tittle" format="string"/> //中间标题的文本内容。 format中文意思是格式,也就是我们所说的类型               
        <attr name="tittleTextSize" format="dimension"/> //中间标题文本大小
        <attr name="tittleTextColor" format="color"/>   //中间标题文本颜色
        <attr name="leftTextColor" format="color"/>    //左边按钮的文本颜色
        <attr name="leftBackground" format="reference|color"/>   //左边按钮的背景
        <attr name="leftText" format="string"/>   //左边按钮的文本
        <attr name="rightTextColor" format="color"/>    //右边按钮的文本颜色
        <attr name="rightBackground" format="reference|color"/>  // 右边按钮的背景
        <attr name="rightText" format="string"/>   //右边按钮的文本
    </declare-styleable>
</resources>

2、定义一个类获取xml的属性实现View

新建一个类名称为TopBar并继承RelativeLayout 实现构造函数 public TopBar(Context context, AttributeSet attrs),

这里一定要注意构造函数有两个参数代码如下:

package com.example.test;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class TopBar extends RelativeLayout {
	// 定义显示的控件
	private Button leftButton, rightButton;
	private TextView tvTittle;

	// 左边Button的属性
	private int leftTextColor;
	private Drawable leftBackground;
	private String leftText;

	// 右边Button的属性
	private int rightTextColor;
	private Drawable rightBackground;
	private String rightText;

	// 中间Title的属性
	private String tittle;
	private float tittleTextSize;
	private int tittleTextColor;
	// 设置三个控件的格式 或者说是布局  LayoutParams可以设置左右按钮和中间文本的布局
	private LayoutParams leftParams, rightParams, tittleParams;

	
	/**
	 * 在构造函数中完成控件的初始化 获取xml中的属性  并将xml中的属性赋值给我们在类中定义的与之对应的变量
	 * 
	 * @param context
	 * @param attrs
	 */
	@SuppressLint("NewApi")
	public TopBar(Context context, AttributeSet attrs) {
		super(context, attrs);
		//重要的数据结构   通过TypedArray我们可以获取到atts.xml文件中的属性内容  
		TypedArray ta = context.obtainStyledAttributes(attrs,
				R.styleable.TopBar);                          *//R.styleable.TopBar就是xml文件中定义的名称*
		leftTextColor = ta.getColor(R.styleable.TopBar_leftTextColor, 0);   *//TopBar_leftTextColor:安卓系统自动把我们atts.xml中定义的属性重新命名  命名规则:控件名称+下划线+属性名称*
		leftBackground = ta.getDrawable(R.styleable.TopBar_leftBackground);
		leftText = ta.getString(R.styleable.TopBar_leftText);

		rightTextColor = ta.getColor(R.styleable.TopBar_rightTextColor, 0);
		rightBackground = ta.getDrawable(R.styleable.TopBar_rightBackground);
		rightText = ta.getString(R.styleable.TopBar_rightText);

		tittle = ta.getString(R.styleable.TopBar_tittle);
		tittleTextColor = ta.getColor(R.styleable.TopBar_tittleTextColor, 0);
		tittleTextSize = ta.getDimension(R.styleable.TopBar_tittleTextSize, 0);

		ta.recycle();//回收系统资源


		*//因为不是Activity不能用findViewById(),   所以我们new出三个控件*
		leftButton = new Button(context);
		rightButton = new Button(context);
		tvTittle = new TextView(context);
		
		//为左边Button设置我们在xml文件中自定义的属性
		leftButton.setTextColor(leftTextColor);
		leftButton.setBackground(leftBackground);
		leftButton.setText(leftText);
		
		//为右边Button设置我们在xml文件中自定义的属性
		rightButton.setTextColor(rightTextColor);
		rightButton.setBackground(rightBackground);
		rightButton.setText(rightText);

		//为中间Tittle设置我们在xml文件中自定义的属性
		tvTittle.setText(tittle);
		tvTittle.setTextColor(tittleTextColor);
		tvTittle.setTextSize(tittleTextSize);
		tvTittle.setGravity(Gravity.CENTER);    //布局为居中

		setBackgroundColor(0xFFF59563);   //设置TopBar的背景颜色

		// 设置左边Button的布局
		// 宽:WRAP_CONTENT 高:WRAP_CONTENT 布局:居左对齐
		//addRule()方法可以设置Button的布局
		leftParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);
		leftParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, TRUE);
		addView(leftButton, leftParams);

		// 右边按钮的属性
		// 宽:WRAP_CONTENT 高:WRAP_CONTENT 布局:居右对齐
		rightParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);
		rightParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, TRUE);
		addView(rightButton, rightParams);

		// 中间Tittle的属性
		tittleParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
				ViewGroup.LayoutParams.MATCH_PARENT);
		tittleParams.addRule(RelativeLayout.CENTER_IN_PARENT, TRUE);
		addView(tvTittle, tittleParams);

		
	}

}

3、引用自定义View

在上述两步中,我们就已经完成了自定义控件,下边最重要的就是该怎么用它了,其实用法和我们平时基本的View用法是一样的,在activity_main.xml文件中只需要我们加上一点东西即可。还是看代码:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:custom="http://schemas.android.com/apk/res/com.example.test"  //**重点内容:当我们使用自定义控件时,需要在此处声明控件的完整包名 注意是包名 例如:com.example.test   (AndroidStudio用户可以在res/  不写包名,,而直接写res/auto)
       还有更重要的一点就是名称custom  这个在下边设置属性的时候会用到**
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >
    
    **//开始使用自定义View,注意要加上完整的类名   注意是类名**
    <com.example.test.TopBar
        android:id="@+id/topbar"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        custom:tittle="OKOKOK"            //**重点内容:上边所说的custom,在这里用到了,大家会注意到设置宽度、高度、id时前面的关键字是“android:”
        这是因为这些属性是安卓本身的属性,而当我们设置自己在xml文件中的属性时,就不能再用“android:”了,而是用我们上边声明的“ custom:”**
        custom:tittleTextSize="10sp"
        custom:tittleTextColor="#FFFFFF"
        
        custom:leftTextColor="#FFFFFF"
        custom:leftBackground="@android:color/holo_purple"
        custom:leftText="LEFT"
        
        custom:rightTextColor="#FFFFFF"
        custom:rightBackground="@android:color/darker_gray"
        custom:rightText="right"
        ></com.example.test.TopBar>

</RelativeLayout>

好了,到这里我相信你的app就应该已经能够跑起来了 哈哈 是不是很简单,,,下一篇我会进阶继续讲一下如何给自定义控件设置监听事件,用接口回调机制完成Button的onClick()方法。加油!

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要在QWidget中实现顶部导航,可以使用QTabBar 或QToolBar,这两个件都可以实现类似的效果。 使用QTabBar: QTabBar是一个选项卡件,可以在其中添加多个选项卡,并且可以自定义选项卡的样式。在QWidget中使用QTabBar可以实现顶部导航的效果。 示例代码: ```python from PyQt5.QtWidgets import QApplication, QWidget, QTabBar, QVBoxLayout class TopBar(QWidget): def __init__(self): super().__init__() # 创建一个QTabBar对象 self.tab_bar = QTabBar() # 设置选项卡的样式 self.tab_bar.setExpanding(True) self.tab_bar.setStyleSheet("QTabBar::tab { height: 35px; width: 100px; }") # 添加选项卡 self.tab_bar.addTab("首页") self.tab_bar.addTab("消息") self.tab_bar.addTab("设置") # 创建一个垂直布局,并将QTabBar添加到布局中 layout = QVBoxLayout() layout.addWidget(self.tab_bar) # 设置QWidget的布局 self.setLayout(layout) if __name__ == '__main__': app = QApplication([]) bar = TopBar() bar.show() app.exec_() ``` 使用QToolBar: QToolBar是一个工具件,可以在其中添加多个工具按钮,并且可以自定义工具按钮的样式。在QWidget中使用QToolBar可以实现顶部导航的效果。 示例代码: ```python from PyQt5.QtWidgets import QApplication, QWidget, QToolBar, QAction class TopBar(QWidget): def __init__(self): super().__init__() # 创建一个QToolBar对象 self.tool_bar = QToolBar() # 设置工具按钮的样式 self.tool_bar.setIconSize(QSize(32, 32)) self.tool_bar.setStyleSheet("QToolButton { border: none; }") # 添加工具按钮 home_action = QAction(QIcon("home.png"), "首页", self) message_action = QAction(QIcon("message.png"), "消息", self) setting_action = QAction(QIcon("setting.png"), "设置", self) self.tool_bar.addAction(home_action) self.tool_bar.addAction(message_action) self.tool_bar.addAction(setting_action) # 将QToolBar添加到QWidget中 self.addToolBar(self.tool_bar) if __name__ == '__main__': app = QApplication([]) bar = TopBar() bar.show() app.exec_() ``` 注意:以上代码中的图片文件需要自己准备。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值