一个简单的android电池显示layout

本文介绍了如何使用自定义ProgressBar和ImageView在Android中创建一个显示电池电量和充电状态的布局。通过调整ProgressBar和ImageView的位置,实现电量比例的显示,同时通过覆盖的ImageView来表示充电情况。

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

思想:progressbar控制电量显示,再加上一个imageview覆盖再上层用于表示充电状态,右边加一个imageview表示电池头部

其实直接在view上自己画会更简单一些,同时也好控制各种位置,但这里暂时不这么做。


以下是layout部分:


自定义progressbar:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
 
    <!-- 背景  gradient是渐变,corners定义的是圆角 -->
    <item android:id="@android:id/background">
        <nine-patch 
            android:src="@drawable/battery_empty_body"
            android:dither="true" />
    </item>
    <!-- 进度条 -->
    <item android:id="@android:id/progress">
        <clip>
            <shape>
                <corners android:radius="0dp" />
                <solid android:color="#646463" />
            </shape>
        </clip>
    </item>
 
</layer-list>

这里背景图使用9.png,方便控制各种大小,不会出现形变啥的。


电池身体:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

	<ProgressBar 
		android:id="@+id/pgb_battery"
		android:layout_width="fill_parent"
		android:layout_height="fill_parent"
		android:max="100"
		android:progress="50"
		android:progressDrawable="@drawable/progressbar_battery"
		style="?android:attr/progressBarStyleHorizontal" />
	 
	<ImageView 
		android:id="@+id/img_battery_charing"
		android:layout_width="fill_parent"
		android:layout_height="fill_parent"
		android:background="@drawable/battery_charging"
		android:contentDescription="@string/nothing" />

</RelativeLayout>

这里用一个imageview作为充电标志。没有充电时,可以设置为invisible。

之所有所有的都用fillparent是因为方便控制放大缩小。


完整电池:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

	<ImageView 
		android:id="@+id/img_battery_head"
		android:layout_width="wrap_content"
		android:layout_height="fill_parent"
		android:background="@drawable/battery_empty_head"
		android:contentDescription="@string/nothing"
		android:layout_alignParentRight="true" />
    	
	<include
	    android:id="@+id/layout_battery_inner"
	    android:layout_toLeftOf="@id/img_battery_head"
	    android:layout_width="fill_parent"
	    android:layout_height="fill_parent"
	    layout="@layout/layout_battery_body" />

</RelativeLayout>



使用:

	<include
	    android:id="@+id/layout_battery"
	    android:layout_width="30dp"
	    android:layout_height="15dp"
	    layout="@layout/layout_battery" />

使用时指定一下大小即可。如果不指定大小,会出现全屏。这个待解决。


效果类似这样:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值