您的位置:首页 > 移动开发 > Android开发

Android编程实用小技巧

2015-09-08 18:05 441 查看
1、密码的显示与隐藏的转换方式

EditText loginEtPwd = ...
// 设置EditText的密码为可见的
loginEtPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());

// 设置EditText密码为隐藏的
loginEtPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());

Editable editable = loginEtPwd.getText();
// 将光标设置在文字末尾,如去掉此段则光标会跑到密码前面
Selection.setSelection(editable, editable.toString().length());


2、关闭软盘(可以设置在onTouch中点击屏幕关闭软盘)

// 在触摸事件中执行关闭软盘操作
public boolean onTouchEvent(MotionEvent event) {
// 得到InputMethodManager对象,将软盘隐藏代码
InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(getCurrentFocus().getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
return super.onTouchEvent(event);
}


3、单位转换器TypedValue

TypedValue位于android.util.TypedValue,该类提供一个静态的单位转换方法:

static float applyDimension(int unit, float value, DisplayMetrics metrics)
可以将其简单的封装做成一个单位转换工具类。如像素px与dp的转化:

TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, context.getResources().getDisplayMetrics());


4、判断网络是否连接

private boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null) {
} else {
// 判断网络连接
NetworkInfo[] info = cm.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}


5、如何设置沉浸式状态栏

设置该特性时android版本必须大于等19才能使用。用法很简单,如下:

a、设置窗口属性

getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
b、设置被沉浸控件的xml属性

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#f0ff"
    android:orientation="vertical" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:background="#f00"
        android:clipToPadding="true"
        android:fitsSystemWindows="true"
        android:text="TextView" />
</LinearLayout>


注意:不同的设置会有不同的效果,只有上面的顺序可以设置同iOS的效果。

设置效果如下图:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: