Android实现显示电量的控件代码

下面介绍了Android实现显示电量的控件代码,具体代码如下:

1、目录结构,本人是使用安卓死丢丢。

Android实现显示电量的控件代码

2、运行界面,输入框中输入数值,点击刷新,会再电池中显示出相应的电量

Android实现显示电量的控件代码

3、绘制自定义电池控件,首先,新建一个类BatteryState继承View

private Context mContext; 
private float width; 
private float height; 
private Paint mPaint; 
private float powerQuantity=0.5f;//电量 

要使用到的变量

public BatteryState(Context context) { 
  super(context); 
  mContext=context; 
  mPaint = new Paint(); 
 
} 
 
public BatteryState(Context context, AttributeSet attrs) { 
  super(context, attrs); 
  mContext=context; 
  mPaint = new Paint(); 
} 
 
public BatteryState(Context context, AttributeSet attrs, int defStyleAttr) { 
  super(context, attrs, defStyleAttr); 
  mContext=context; 
  mPaint = new Paint(); 
} 

三个构造方法,自定义控件的时候一般会把这三个构造方法写出来,便于在layout中使用或者直接定义,其中AttributeSet是当使用xml文件定义该控件时引用的属性集

@Override 
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
//    计算控件尺寸 
    super.onMeasure(widthMeasureSpec, heightMeasureSpec); 
  } 
 
  @Override 
  protected void onDraw(Canvas canvas) { 
//绘制界面 
    super.onDraw(canvas); 
    Bitmap batteryBitmap=ReadBitMap(mContext, R.drawable.battery_empty);//读取图片资源 
    width=batteryBitmap.getWidth(); 
    height=batteryBitmap.getHeight(); 
    if (powerQuantity>0.3f&&powerQuantity<=1) { 
//      电量少于30%显示红色 
      mPaint.setColor(Color.GREEN); 
    } 
    else if (powerQuantity>=0&&powerQuantity<=0.3) 
    { 
      mPaint.setColor(Color.RED); 
    } 
//    计算绘制电量的区域 
    float right=width*0.94f; 
    float left=width*0.21f+(right-width*0.21f)*(1-powerQuantity); 
    float tope=height*0.45f; 
    float bottom=height*0.67f; 
 
    canvas.drawRect(left,tope,right,bottom,mPaint); 
    canvas.drawBitmap(batteryBitmap, 0, 0, mPaint); 
  } 

由于我们定义的控件时一个单个控件,不是容器控件,所以我只重写了onMeasure、onDraw分别用来计算大小和绘制界面,根据背景图片来计算要绘制的区域

  public void refreshPower(float power) 
{ 
  powerQuantity=power; 
  if (powerQuantity>1.0f) 
    powerQuantity=1.0f; 
  if (powerQuantity<0) 
    powerQuantity=0; 
  invalidate(); 
} 

刷新控件

4、在xml文件中定义:

<LinearLayout 
  android:layout_width="wrap_content" 
  android:layout_marginLeft="30dp" 
  android:layout_height="30dp"> 
  <com.example.administrator.batterytest.BatteryState 
    android:id="@+id/bs_power" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" /> 
</LinearLayout> 

5、在Activity中使用

mBtnTry = (TextView) findViewById(R.id.btn_try); 
    mBtnTry.setText("刷新电量"); 
//    mBtnTry.setBackground(getResources().getDrawable(R.drawable.maxwell_sun_5_bar)); 
    mBsPower = (BatteryState) findViewById(R.id.bs_power); 
    mBtnTry.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
        float power = Integer.parseInt(mEtPower.getText().toString()); 
        float p = power / 100; 
        mBsPower.refreshPower(p); 
      } 
    }); 

希望本文所述对你有所帮助,Android实现显示电量的控件代码就给大家介绍到这里了。希望大家继续关注我们的网站!