在之前的基础上
在 res 文件夹下面: 添加一个 drawable/local_me.xml
localme_cml
<selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_checked="true" android:drawable="@drawable/on" /> <!-- pressed --> <item android:drawable="@drawable/off" /> <!-- default/unchecked --> </selector>
主程序:
package com.example.handlightactivity; import android.app.Activity; import android.hardware.Camera; import android.hardware.Camera.Parameters; import android.os.Bundle; import android.os.Process; import android.view.View; import android.view.View.OnClickListener; import android.view.WindowManager; import android.widget.ToggleButton; /** * * @author love * * 原理: * 就是通过 点击按钮, * 当 点击按钮的时候 打开闪光灯。 * 关闭 按钮的时候 关闭闪光灯 * * * */ public class MainActivity extends Activity implements OnClickListener { private ToggleButton toggleButton; private Camera camera = Camera.open(); /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toggleButton = (ToggleButton) this.findViewById(R.id.toggleButton1); toggleButton.setOnClickListener(this); //保持屏幕 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } @Override public void onClick(View v) { ToggleButton tb = (ToggleButton) v; Camera.Parameters param = camera.getParameters(); if(!tb.isChecked()){ // open the camera flash! param.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); toggleButton.setBackgroundColor(0x30ffffff); // on open on.jpg tb.setBackgroundDrawable(getResources().getDrawable(R.drawable.on)); }else{ param.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); toggleButton.setBackgroundColor(0xffffffff); // off open the off.jpg tb.setBackgroundDrawable(getResources().getDrawable(R.drawable.off)); } camera.setParameters(param); } @Override protected void onPause() { // camera.release(); // Process.killProcess(Process.myPid()); super.onPause(); } }
效果图:
Android开发----------- 手电筒改进版本,布布扣,bubuko.com
时间: 2024-10-29 19:06:33