Android小技巧总结(不定时更新)

1. Sticky BroadCast 异步广播

    普通的Broadcast的发送就不说了,说说异步的广播。

    以下摘自官方文档:

    Perform a sendBroadcast(Intent) that is "sticky," meaning the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of registerReceiver(BroadcastReceiver, IntentFilter). In all other ways, this behaves the same as sendBroadcast(Intent).

You must hold the BROADCAST_STICKY permission in order to use this API. If you do not hold that permission, SecurityException will be thrown.

简言之:处理完之后的Intent 依然存在,直到你把它去掉。发这个广播需要权限<uses-permission android:name="android.permission.BROADCAST_STICKY" />

这个方法的好处是当接收这个broadcast的receiver挂掉重启后依然能接收到这个广播而不需要广播发送者重新发送广播。


2.SQLiteOpenHelper

在操作数据库的时候常常new 一个SQLdatabase来进行操作,这样如果忘了close就会报错了。但如果继承自SQLiteOpenHelper类,然后在其中加入如下代码

public static synchronized SqliteHelper getHelper(Context context)
	    {
	        if (instance == null)
	            instance = new SqliteHelper(context, "database", null, 1);
	 
	        return instance;
	    }
这样在其他类里面只需要使用getHelper(getContext()).getWritableDatabase();就能获得一个可以读写的SQLdatabase,同时操作完毕数据库后不需要调用close()方法来关闭数据库,随时随地操作,不用担心没有调用close()而出错,因为在程序结束的时候会自动关闭这个数据库的。


3.工具类中获取Context

在自己的工具类中想要取得一个context来进行发送广播等的操作,可以新建一个继承子Application的类,然后在该类中将context传给工具类,比如:

public class myApp extends Application {
	@Override
	public void onCreate() {
		Util.instance().setContext(this);
	}
}
这样在工具类Util中就可以取得应用的context了,然后你就可以为所欲为了~~

4.设置控件背景

这里以checkbox为例,如果要频繁改变checkbox的样式,如果从代码里更改,不仅麻烦而且影响代码质量,可以通过如下方法解决:

在drawable下新建一个mycheckbox.xml文件,内容如下:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
     <item android:state_checked="true" android:state_enabled="false"
        android:drawable="@drawable/checked_false"/>
     <item android:state_checked="true"   
         android:drawable="@drawable/checked" />
     <item android:state_checked="false" android:state_enabled="false" 
         android:drawable="@drawable/unchecked_false" />
     <item android:state_checked="false"   
         android:drawable="@drawable/unchecked" />
</selector>
然后在在values下新建一个styles.xml文件如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="MyCheckBox" parent="@android:style/Widget.CompoundButton.CheckBox">
   		<item name="android:button">@drawable/mycheckbox</item>
   </style>
</resources>
完成以上代码后只要在你的checkbox布局文件里加上如下代码:

	<CheckBox 
	    android:id="@+id/checkbox"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    style="@style/MyCheckBox"/>
即加上style这句话就可以呈现出各种状态的checkbox了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值