Android之开发常用小功能(持续更新中。。。)

Android之开发常用小功能

有的时候会用到很多小的东西,但不可能全部都记住,每次都要到网上去查,很麻烦。所以,我把这些东西整理到一起,在用的时候直接拿过去用就可以了。

一.android资源文件转换为drawable、Bitmap

转drawable

Resources resources = getResources();
Drawable drawable = resources.getDrawable(R.color.colorAccent);

转bitmap

1
Resources r = this.getContext().getResources();
InputStream is = r.openRawResource(R.drawable.icon);
BitmapDrawable  bmpDraw = new BitmapDrawable(is);
Bitmap bmp = bmpDraw.getBitmap();

2
Resources r = getResources();
Bitmap bmp=BitmapFactory.decodeResource(r, R.drawable.icon);

3
InputStream is = getResources().openRawResource(R.drawable.icon);  
Bitmap mBitmap = BitmapFactory.decodeStream(is);

二.判断网络连接状态&类型

状态

    public static boolean getWebStatus(Context context){
        ConnectivityManager manager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo gprs = manager
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        NetworkInfo wifi = manager
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (gprs!=null && wifi!=null) {
            if (!gprs.isConnected() && !wifi.isConnected()) {
                return false;
            } else {
                return true;
            }
        }else {
            return false;
        }
    }

类型

//获取当前的网络状态 -1:没有网络 1:WIFI网络2:wap网络3:net网络
public static int getAPNType(Context context) {
        int netType = -1;
        int WIFI = 1;
        int CMWAP = 2;
        int CMNET = 3;

        ConnectivityManager connMgr = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo == null) {
            return netType;
        }
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_MOBILE) {
            if (networkInfo.getExtraInfo().toLowerCase().equals("cmnet")) {
                netType = CMNET;
            } else {
                netType = CMWAP;
            }
        } else if (nType == ConnectivityManager.TYPE_WIFI) {
            netType = WIFI;
        }
        return netType;
    }

三.解决因为连续点击而造成的问题

public class PreventDoubleHit {
    private static long lastClickTime;
    /**
     * 是否点击过快(暂时为1秒)
     * @return ture 点击过快,false 正常点击
     */
    public synchronized static boolean isFastClick(String fastText) {
        long time = System.currentTimeMillis();   
        if ( time - lastClickTime < 1000) {
            ShowToast.showToast(fastText, 1000);
            return true;   
        }   
        lastClickTime = time;   
        return false;   
    }
}

四.Toast的显示时间不会过长

public class ShowToast {
    private static Toast mToast;
    private static Handler mHandler;
    private ShowToast(){
        if (mHandler == null) {
            Looper.prepare();
            mHandler = new Handler();
            Looper.loop();
        }
    }
    private static Runnable r = new Runnable() {
        public void run() {
            mToast.cancel();
        }
    };

    public static void showToast(Context mContext, String text, int duration) {
        if (mHandler == null) {
            mHandler = new Handler();
        }
        mHandler.removeCallbacks(r);
        if (mToast != null){
            mToast.setText(text);
        }
        else{
            mToast = Toast.makeText((Context) mContext, text, Toast.LENGTH_SHORT);
        }
        mHandler.postDelayed(r, duration);
        mToast.show();
    }

    public static void showToast(Context mContext, int resId, int duration) {
        showToast(mContext, mContext.getResources().getString(resId), duration);
    }

    public static void showToast(String text, int duration) {
        showToast(App.getApp(), text, duration);
    }

    public static void showToast(int resId, int duration) {
        showToast(App.getApp(), App.getApp().getResources().getString(resId), duration);
    }
}

五.样式(style)的使用

1.对共有属性进行抽取

示例:对TextView属性进行抽取

//样式文件
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <style name="text">
        <item name="android:gravity">center</item>
        <item name="android:textColor">@android:color/holo_green_dark</item>
        <item name="android:textSize">20dp</item>
        <item name="android:textStyle">bold</item>
        <item name="android:padding">20dip</item>
        <item name="android:background">@android:color/holo_orange_light</item>
    </style>
</resources>

//使用
<TextView 
        android:id="@+id/text1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="样式"
        style="@style/text"/>

六.只带边框的圆角矩形

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <!-- 用于设置渐变填充色 -->
    <gradient
        android:endColor="#ffffff"
        android:startColor="#ffffff" />

    <!-- 设置填充颜色 -->
    <solid android:color="#ffffff" />

    <!-- 设置描边颜色与宽度 -->
    <stroke
        android:width="1dp"
        android:color="#ffffff" />

    <!-- 设置四个角的角度 -->
    <corners
        android:bottomLeftRadius="10dp"
        android:bottomRightRadius="10dp"
        android:topLeftRadius="10dp"
        android:topRightRadius="10dp" />

    <!-- 内容距离边界的距离 -->
    <padding
        android:bottom="20dp"
        android:left="20dp"
        android:right="20dp"
        android:top="20dp" />
</shape>

gradient节点主要配置起点颜色、终点颜色、中间点的坐标、中间点的颜色、渐变角度(90度为上下渐变,0为左右渐变)。

七.获取当前系统时间

获取当前系统时间

SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
//获取当前时间
Date curDate = new Date(System.currentTimeMillis());      
String str = formatter.format(curDate);

获取当前系统时间是24制 还是12制

ContentResolver cv = this.getContentResolver();
String strTimeFormat = android.provider.Settings.System.getString(cv,  
android.provider.Settings.System.TIME_12_24);  
if(strTimeFormat.equals("24"))  
{  
   Log.i("activity","24");  
}

利用Calendar获取获取时间

Calendar c = Calendar.getInstance();  
取得系统日期:year = c.get(Calendar.YEAR)  
           month = c.get(Calendar.MONTH)  
           day = c.get(Calendar.DAY_OF_MONTH)  
取得系统时间:hour = c.get(Calendar.HOUR_OF_DAY);  
            minute = c.get(Calendar.MINUTE)  

利用Time获取(这个只有24小时制)

// or Time t=new Time("GMT+8"); 加上Time Zone资料
Time t=new Time();
t.setToNow(); // 取得系统时间
int year = t.year;  
int month = t.month;  
int date = t.monthDay;  
int hour = t.hour; // 0-23
int minute = t.minute;
int second = t.second;

八.时间转换

1.字符串转换成日期类型

//方法一
Date date = new Date("2000-01-01");
//方法二
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date=sdf.parse("2000-01-01");

2.日期转换成字符串

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = enw Date();
String str = sdf.format(date);

九.比较时间的大小

//获取时间差
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try{
    Date d1 = sdf.parse("2000-02-02 02:02:02");
    Date d2 = sdf.parse("2000-01-01 01:01:01");
    long l = d1.getTime() - d2.getTime();
    long day = l/(24*60*60*1000);
    long hour=(l/(60*60*1000)-day*24);
    long min=((l/(60*1000))-day*24*60-hour*60);
    long s=(l/1000-day*24*60*60-hour*60*60-min*60);
    System.out.println(""+day+"天"+hour+"小时"+min+"分"+s+"秒");
}catch(Exception e){}

//比较时间大小
String s1="2008-01-25 09:12:09";
String s2="2008-01-29 09:12:11";
DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
try
{
c1.setTime(df.parse(s1));
c2.setTime(df.parse(s2));
}catch(java.text.ParseException e){
System.err.println("格式不正确");
}
int result=c1.compareTo(c2);
if(result==0)
System.out.println("c1相等c2");
else if(result<0)
System.out.println("c1小于c2");
else
System.out.println("c1大于c2");

十.隐藏屏幕中虚拟键盘

隐藏所有虚拟键盘

InputMethodManager imm =  (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
if(imm != null) {         imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(),0);
}

隐藏指定EditText的虚拟键盘

imm.hideSoftInputFromWindow(edit.getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值