Android常用代码4

欢迎来到风的博客

-设置全屏的方法

-添加自定义控件属性

###设置全屏的方法
在java代码中设置,需要将代码放在setContentView()之前

1
2
3
4
//set no title bar
requestWindowFeature(Window.FEATURE_NO_TITLE);
//set to full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

在AndroidManifest.xml中配置

1
android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"

###添加自定义控件属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
1. 在res/values文件下定义一个attrs.xml文件.代码如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyCustomAttr">
<!--
说明: reference:参考某一资源ID
使用:Customxmlns:AttrBackground = "@drawable/..."
-->
<attr name="AttrBackground" format="reference" />
<!--
说明: color:颜色值
使用:Customxmlns:AttrColor = "@color/..."
-->
<attr name="AttrColor" format="color" />
<!--
说明: boolean:布尔值
使用:Customxmlns:CustomBoolean = "true"
-->
<attr name="CustomBoolean" format="boolean" />
<!--
说明: dimension:尺寸值
使用:Customxmlns:CustomDimension = "100dip"
-->
<attr name="CustomDimension" format="dimension" />
<!--
说明: float:浮点值
使用:Customxmlns:CustomFloat = "0.8"
-->
<attr name="CustomFloat" format="float" />
<!--
说明: integer:整型值
使用:Customxmlns:CustomInteger = "100"
-->
<attr name="CustomInteger" format="integer" />
<!--
说明: string:字符串
使用:Customxmlns:CustomString = "@string/..."
-->
<attr name = "CustomString" format="string" />
<!--
说明: fraction:百分数
使用:Customxmlns:CustomFraction = "50%"
-->
<attr name = "CustomFraction" format="fraction" />
<!--
说明: enum:枚举值
使用:Customxmlns:CustomOrientation = "vertical"
-->
<attr name="CustomOrientation">
<enum name="horizontal" value="0" />
<enum name="vertical" value="1" />
</attr>
<!--
说明: flag:位或运算
使用:Customxmlns:CustomWindowSoftInputMode = "stateUnspecified | stateUnchanged"
-->
<attr name="CustomWindowSoftInputMode">
<flag name="stateUnspecified" value="0" />
<flag name="stateUnchanged" value="1" />
<flag name="stateHidden" value="2" />
</attr>
<!--
说明: 属性定义时可以指定多种类型值
使用:Customxmlns:CustomBackground = "@drawable/图片ID|#00FF00"
-->
<attr name="CustomBackground" format="reference|color" />
</declare-styleable>
</resources>
2. 在布局xml中如下使用该属性(其中com.customattrs为包名):
<com.customattrs.MyCustomView
xmlns:canremovechild="http://schemas.android.com/apk/res/com.customattrs"
android:layout_width="match_parent"
android:layout_height="match_parent"
canremovechild:CustomBoolean="true" />
3. 在自定义组件中,可以如下获得xml中定义的值:
在MyCustomView.java中的构造函数中:
public MyCustomView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomAttr);
boolean canRemoveChild = a.getBoolean(R.styleable.MyCustomAttr_CustomBoolean, false);
a.recycle();
}

listview优化

#欢迎来到风的博客

###listview优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// LayoutInflater inflater = LayoutInflater.from(context);
// layout = (LinearLayout) inflater.inflate(R.layout.item, null);
// TextView tvName = (TextView) layout.findViewById(R.id.tvName);
// TextView tvNumber = (TextView) layout.findViewById(R.id.tvNumber);
// tvName.setText(list.get(position).getName());
// tvNumber.setText(list.get(position).getNumber());
//listview优化
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.item, null);
holder = new ViewHolder();
holder.tvName = (TextView) convertView.findViewById(R.id.tvName);
holder.tvNumber = (TextView) convertView.findViewById(R.id.tvNumber);
holder.tvName.setText(list.get(position).getName());
holder.tvNumber.setText(list.get(position).getNumber());
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
holder.tvName.setText(list.get(position).getName());
holder.tvNumber.setText(list.get(position).getNumber());
}
//return layout
return convertView;
}
private static class ViewHolder{
TextView tvName;
TextView tvNumber;
}

android常用代码3

欢迎来到风的博客

-让AlertDialog在按钮被点击后不关闭

-闪光灯的开启和关闭

-让EditText失去焦点而不弹出软键盘

-强制EditText不弹出软键盘


###让AlertDialog在按钮被点击后不关闭

1
2
3
4
5
6
7
8
9
10
11
12
/* *
* * 设定使用AlertDialog时,当点击其中的按钮时,是否自动退出AlertDialog,disableOrEnable为true时退出,false时不退出
* */
private void disableOrEnableBtnCloseOnAlertDialog(DialogInterface dialog, boolean disableOrEnable){
try {
Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
field.setAccessible(true);
field.set(dialog, disableOrEnable);
} catch (Exception e) {
e.printStackTrace();
}
}

###闪光灯的开启和关闭

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!-- 打开Camera的权限 -->
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.autofocus" />
<!-- 开启闪光灯权限 -->
<uses-permission android:name="android.permission.FLASHLIGHT" />
private static Camera camera = null;
private static Parameters parameters_light = null;
public static void turnOnLight() {
if(null == camera){
camera = Camera.open();
parameters_light = camera.getParameters();
parameters_light.setFlashMode(Parameters.FLASH_MODE_TORCH);// 开启闪光灯
camera.setParameters(parameters_light);
}
}
public static void turnOffLight() {
if(null != camera){
parameters_light.setFlashMode(Parameters.FLASH_MODE_OFF);// 关闭闪光灯
camera.setParameters(parameters_light);
camera.release();
camera = null;
}
}

###让EditText失去焦点而不弹出软键盘

######只需要让其他的控件获取焦点即可:

1
2
mTv_title.setFocusable(true);
mTv_title.setFocusableInTouchMode(true);

###强制EditText不弹出软键盘

1
mEt.setInputType(InputType.TYPE_NULL);

android常用代码2

欢迎来到风的博客

-获取控件在屏幕中的位置

-捕获按键事件

-振动效果

-监听Activity加载完毕

###获取控件在屏幕中的位置

1
2
3
4
int[] locations = new int[2];
view.getLocationOnScreen(locations);
int x = locations[0];//获取组件当前位置的横坐标
int y = locations[1];//获取组件当前位置的纵坐标

###捕获按键事件

1
2
3
4
5
6
7
8
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_BACK){
}
return super.onKeyDown(keyCode, event);
}

###振动效果

#####首先就要得到使用权限,在menifest.xml里面声明一下就可以了

1
<uses-permission android:name="android.permission.VIBRATE"/>

#####然后就可以在程序里面使用 振动了,下面可以得到振动效果的类

1
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

#####最后就是控制振动时间

1
vibrator.vibrate(100);

#####在需要的地方做上面的操作就可以完成振动的效果了。

###监听Activity加载完毕

#####这个onWindowFocusChanged指的是这个Activity得到或者失去焦点的时候 就会call.

#####也就是说 如果你想要做一个Activity一加载完毕,就触发什么的话 完全可以用这个!!

1
2
3
4
5
@Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
}

android常用代码1

欢迎来到风的博客

-Activity跳转代码模板

-Toast使用

-获取当前系统时间

-获取屏幕宽度和高度

###Activity跳转代码模板

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
Intent intent = new Intent(A.this, B.class);
Bundle bundle = new Bundle();
bundle.putString("key", "value");
bundle.putInt("key", 0);
intent.putExtras(bundle);
startActivity(intent);
-------------------------------------------------------------------------------
startActivityForResult(intent, requestCode);
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
}
}
--------------------------------------------------------------------------------
返回传递参数:
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putString("key", "value");
bundle.putInt("key", 0);
intent.putExtras(bundle);
setResult(RESULT_OK, intent);
finish();
返回不传递参数:
setResult(RESULT_OK);
finish();

###Toast使用

1
2
3
4
5
6
7
Toast.makeText(getApplicationContext(), "默认Toast样式", Toast.LENGTH_SHORT).show();
private void makeTip(String info) {
Toast toast = Toast.makeText(getApplicationContext(), info, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}

###获取当前系统时间

1
2
3
4
5
6
7
8
//12小时制
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String date = sdf.format(new java.util.Date());
//24小时制
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = sdf.format(new java.util.Date());

###获取屏幕宽度和高度

1
2
3
4
5
6
7
public static int displayWidth; //屏幕宽度
public static int displayHeight; //屏幕高度
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
displayWidth = displayMetrics.widthPixels;
displayHeight = displayMetrics.heightPixels;

#####但是,需要注意的是,在一个低密度的小屏手机上,仅靠上面的代码是不能获取正确的尺寸的。比如说,一部240x320像素的低密度手机,如果运行上述代码,获取到的屏幕尺寸是320x427。因此,研究之后发现,若没有设定多分辨率支持的话,Android系统会将240x320的低密度(120)尺寸转换为中等密度(160)对应的尺寸,这样的话就大大影响了程序的编码。所以,需要在工程的AndroidManifest.xml文件中,加入supports-screens节点,具体的内容如下:

1
2
3
4
5
6
<supports-screens
android:smallScreens="true"
android:normalScreens="true"
android:largeScreens="true"
android:resizeable="true"
android:anyDensity="true" />

#####这样的话,当前的Android程序就支持了多种分辨率,那么就可以得到正确的物理尺寸了。
-原文引自[http://www.67bar.com/archives/1971]