50)dialog样式
51)开启一个提示音
52)从服务器获取json数据
53)创建txt文件,并向其写数据
54)获取状态栏高度
55)获取标题栏高度
56) 截屏代码
57) listview的点击变换背景色
58)自定义主题风格
59)最省代码的按钮监听
60) 在service中使用Toast的方法
61)最简单的等待窗
62) 手机拍照并保持图片
63)获取手机相册中缩略图和原始图
64)根据路径加载sd卡中的图片的方法
65) 加载一张本地高清大图的方法
66)点击两次返回退出
67) 自定义View 自适应宽高
68)将activity变为dialog代码
69)自定义Dialog时,可以给dialog设置自己的风格 R.style.my_tips_dialog
70)sd卡创建文件夹和保存文件
71)自画圆角矩形
72) 根据adapter中的数据来设置listview的高度
73) EditText 是否弹出软键盘的问题
74)UI界面使用EditText时,在注册文件中对该activity添加软键盘属性:
75) 善用Android预定义样式
76)view的抖动效果
77)activity的切换动画
78)listView的setOnItemClickListener方法中可以控制adapter中的组件
79)接口回调标准代码
80)Listview 点击item项后,让item常亮
81)点击组件背景白变灰色
82)自画button,有点击效果
83)View悬浮在所有View之上:
- 获取res里图片资源的id的方法
85)将dp转换为px
86)一个TextView展示多行数据
87)隐藏软键盘
88)ToggleButton开关按钮的使用
89) ObjectAnimator 创建动画
90)开机自启动
91)EditText inputType说明
92)dip,px转换
93)适配
94) 动态添加布局
95) 获取网络连接模式
96)反射方法获取状态栏高度
97)每隔一秒钟向主线程发送数据
98)剪切(Clip)图像资源
99)常用的一些系统属性
100)如果sd卡存在就创建目录,如果没有就将目录创建在缓存
51)开启一个提示音
private void initMusic() {
Uri notification = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_ALARM);
r = RingtoneManager.getRingtone(getApplicationContext(), notification);
if (r.isPlaying()) {
r.stop();
} else {
r.play();
}
}
52)从服务器获取Json数据
HttpPost request = new HttpPost("http://rest.careyou360.com/FamilyRest/getFamilyState");
JSONObject param = new JSONObject();
try {
param.put("restVersion", 1);
param.put("platform", "android");
param.put("familyId", "10000");
param.put("userId", "10000");
StringEntity se = new StringEntity(param.toString()); //绑定到请求 Entry
request.setEntity(se);
// 发送请求
HttpResponse httpResponse = new DefaultHttpClient().execute(request);
//服务器返回的数据
String retSrc = EntityUtils.toString(httpResponse.getEntity());
}
53)创建txt文件,并向其写数据
private void saveData() {
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File sdCardDir = Environment.getExternalStorageDirectory();
File saveFile = new File(sdCardDir, "微心百源Ble名单.txt");
FileOutputStream outStream;
if(backbleList.size()>0&&backbleList!=null){
try {
outStream = new FileOutputStream(saveFile,true);
for (int i = 0; i < backbleList.size(); i++) {
outStream.write(backbleList.get(i).getName().getBytes());
outStream.write(" : ".getBytes());
outStream.write(backbleList.get(i).getAddress().getBytes());
outStream.write("\n".getBytes());
}
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}else{
Toast.makeText(this, "请插入sd卡", Toast.LENGTH_LONG).show();
}
}
54)获取状态栏高度
decorView是window中的最顶层view,可以从window中获取到decorView,然后decorView有个getWindowVisibleDisplayFrame方法可以获取到程序显示的区域,包括标题栏,但不包括状态栏。
Rect frame = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
55)获取标题栏高度
int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
//statusBarHeight是上面所求的状态栏的高度
int titleBarHeight = contentTop - statusBarHeight
56) 截屏代码
private byte[] GetandSaveCurrentImage(){
View view = this.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap b1 = view.getDrawingCache();
// 获取状态栏高度
Rect frame = new Rect();
this.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
Log.i("TAG", "" + statusBarHeight);
int width = this.getWindowManager().getDefaultDisplay().getWidth();
int height = this.getWindowManager().getDefaultDisplay()
.getHeight();
Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height
- statusBarHeight);
view.destroyDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
public Bitmap ScreenShot(Activity context){
// 获取windows中最顶层的view
View view=context.getWindow().getDecorView();
view.buildDrawingCache();
// 获取状态栏高度
Rect rect=new Rect();
view.getWindowVisibleDisplayFrame(rect);
int statusBarHeights = rect.top;
Display display = context.getWindowManager().getDefaultDisplay();
// 获取屏幕宽和高
int widths = display.getWidth();
int heights = display.getHeight();
// 允许当前窗口保存缓存信息
view.setDrawingCacheEnabled(true);
// 去掉状态栏
Bitmap bmp = Bitmap.createBitmap(view.getDrawingCache(), 0,
statusBarHeights, widths, heights - statusBarHeights);
// 销毁缓存信息
view.destroyDrawingCache();
return bmp;
}
57) listview的点击变换背景色
android:listSelector="@drawable/record_item_selector"
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@color/gray" />
<item android:drawable="@color/transparent" />
</selector>
58)自定义主题风格
android:theme="@style/MyAppTheme"
theme.xml文件
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="MyAppTheme" parent="android:Theme">
<item name="android:windowNoTitle">true</item> //没有标题栏
<item name="android:textSize">16sp</item> //默认全局的字体大小
<item name="android:textColor">@color/main_color</item> //默认全局的字体颜色
<item name="android:buttonStyle">@style/btnDefault</item> //自定义按钮
<item name="android:windowBackground">@color/main_background</item> //默认activty的背景颜色
</style>
<style name="btnDefault">
<item name="android:background">@drawable/btn_default_small_normal</item>
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">40dp</item>
</style>
</resources>
59)最省代码的按钮监听
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/begin_record"
android:layout_margin="10dp"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:onClick="doClick"
android:text="@string/begin_record" />
<Button
android:id="@+id/stop_record"
android:layout_margin="10dp"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:onClick="doClick"
android:text="@string/stop_record" />
</LinearLayout>
public void doClick(View view) {
switch (view.getId()) {
case R.id.begin_record:
Toast.makeText(getApplicationContext(), "开始录音", 1).show();
break;
case R.id.stop_record:
Toast.makeText(getApplicationContext(), "停止录音", 1).show();
break;
}
}
60) 在service中使用Toast的方法
private void showMessage(final String msg){
mHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(BleConnectService.this, msg, 1).show();
}
});
}
61)最简单的等待窗
mProgressDialog =ProgressDialog.show(getApplicationContext(), null, "正在加载.....");
62)手机拍照并保存图片
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "temp1.jpg")));
this.startActivityForResult(intent, 1);
63)获取手机相册中缩略图和原始图
获取缩略图:
public void getThumbnail(){
cr = this.getContentResolver();
String[] projection = { Thumbnails._ID, Thumbnails.IMAGE_ID,
Thumbnails.DATA };
Cursor cursor = cr.query(Thumbnails.EXTERNAL_CONTENT_URI, projection,
null, null, null);
if(cur.moveToFirst()){
int _id;
int image_id;
String image_path;
int _idColumn = cursor.getColumnIndex(Thumbnails._ID);
int image_idColumn = cursor.getColumnIndex(Thumbnails.IMAGE_ID);
int dataColumn = cursor.getColumnIndex(Thumbnails.DATA);
do{
_id = cursor.getInt(_idColumn);
image_id = cursor.getInt(image_idColumn);
image_path = cursor.getString(dataColumn);
// Log.i("TAG", image_path);
Thumbnail nail=new Thumbnail();
Log.i("TAG", image_id+"");
nail.setImage_id(image_id+"");
nail.setImage_path(image_path);
list.add(nail);
}while (cur.moveToNext());
}
}
根据缩略图id获取原始图:
protected String getOriginalImagePath(String image_id) {
String path = null;
String[] projection = { Media._ID, Media.DATA };
Cursor cursor = cr.query(Media.EXTERNAL_CONTENT_URI, projection,
Media._ID + "=" + image_id, null, null);
if (cursor != null) {
cursor.moveToFirst();
path = cursor.getString(cursor.getColumnIndex(Media.DATA));
}
return path;
}
64)根据路径加载sd卡中的图片的方法
Bitmap bm = BitmapFactory.decodeFile(filepath);
//将图片显示到ImageView中
img.setImageBitmap(bm);
65) 加载一张本地高清大图的方法:
// url是本地大图的sd卡位置
private Bitmap getoptBitmap(String url) {
BitmapFactory.Options opts = new Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(url,opts);
// 从Options中获取图片的分辨率
int imageHeight = opts.outHeight;
int imageWidth = opts.outWidth;
// 获取Android屏幕的服务
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
int windowHeight = wm.getDefaultDisplay().getHeight();
int windowWidth = wm.getDefaultDisplay().getWidth();
// 计算采样率
int scaleX = imageWidth / windowWidth;
int scaleY = imageHeight / windowHeight;
int scale = 1;
if (scaleX > scaleY && scaleY >= 1) {
scale = scaleX;
}
if (scaleX < scaleY && scaleX >= 1) {
scale = scaleY;
}
opts.inJustDecodeBounds = false;
opts.inSampleSize = scale;
return BitmapFactory.decodeFile(url,opts);
}
66)点击两次返回退出
public boolean onKeyDown(int keyCode, android.view.KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK){
exitBy2Click();
}
return false;
}
private static Boolean isExit = false;
private void exitBy2Click() {
Timer tExit = null;
if (isExit == false) {
isExit = true;
MCToast.show("再按一次退出程序", this);
tExit = new Timer();
tExit.schedule(new TimerTask() {
@Override
public void run() {
isExit = false;
}
}, 2000);
} else {
finish();
}
};
67) 自定义View 自适应宽高
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int measuredHeight = measureHeight(heightMeasureSpec);
int measuredWidth = measureWidth(widthMeasureSpec);
setMeasuredDimension(measuredWidth, measuredHeight);
}
private int measureWidth(int measureSpec) {
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
int result = XScale*data.size();
if (specMode == MeasureSpec.AT_MOST){
result = specSize;
}else if(specMode == MeasureSpec.EXACTLY){
result = specSize;
}
return result;
}
private int measureHeight(int measureSpec) {
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
int result = 500;
if (specMode == MeasureSpec.AT_MOST){
result = specSize;
}else if(specMode == MeasureSpec.EXACTLY){
result = specSize;
}
return result;
}
68)将activity变为dialog代码
在注册文件中写android:theme="@style/loading_dialog"
<style name="loading_dialog" parent="@android:style/Theme.Dialog">
<item name="android:windowFrame">@null</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowNoTitle">true</item>
<item name="android:backgroundDimEnabled">true</item>
<item name="android:windowBackground">@color/transparent</item>
</style>
69)自定义Dialog时,可以给dialog设置自己的风格 R.style.my_tips_dialog
MyTipsDialog dialog = new MyTipsDialog(RecordActivity.this, R.style.my_tips_dialog);
<style name="my_tips_dialog" parent="@android:Theme.Dialog">
<item name="android:windowFrame">@null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowBackground">@color/transparent</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowContentOverlay">@null</item>
</style>
70)sd卡创建文件夹和保存文件
//创建文件夹
public class DataPathUtil {
public static String getDataBasePath() {
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
String parentPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/cwatch_cardio/";
File tempFile = new File(parentPath);
if (!tempFile.exists()) {
tempFile.mkdirs();
}
return parentPath;
}
return null;
}
}
recordFileName = DataPathUtil.getDataBasePath() + "BtData_"+ new Date().getTime() + ".dat";
File ecgFile = new File(recordFileName);
if(ecgFile!= null && ecgFile.exists()){
ecgFile.delete();
}
//创建文件
carmaCarfile = new File(DataPathUtil.getDataBasePath(), String.valueOf(System.currentTimeMillis())+ ".jpg");
71)自画圆角矩形
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 点击效果 -->
<item android:state_pressed="true">
<shape>
<!-- 填充 -->
<solid android:color="@color/gray" />
<!-- 描边 描边的宽度和描边的颜色值 -->
<stroke android:width="1dp" android:color="@color/gray" />
<!-- 圆角 -->
<corners android:topLeftRadius="8dp" android:topRightRadius="8dp" />
<!-- 设置各个方向的间隔 -->
<padding android:bottom="0dp" android:left="10dp" android:right="10dp" android:top="0dp" />
</shape>
</item>
<!-- 默认 -->
<item>
<shape>
<solid android:color="@android:color/white" />
<corners android:topLeftRadius="8dp" android:topRightRadius="8dp" />
</shape>
</item>
</selector>
72) 根据adapter中的数据来设置listview的高度
private void setListViewHeightBasedOnChildren(ExtendedListView listView) {
ListAdapter listAdapter = listView.getAdapter(); //得到该listview的适配器数据多少
if(listAdapter == null){
return;
}
int totalHeight=0;
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
73) EditText 是否弹出软键盘的问题
1.想要一进入activity后,就弹出软键盘的方法是在注册文件activity下添加:
android:windowSoftInputMode="stateVisible|adjustPan"
2. 进入activity后,不弹出软键盘的方法是:
一 在注册文件中添加:android:windowSoftInputMode="adjustUnspecified|stateHidden"
二 让Edittext失去焦点: EditText edit=(EditText)findViewById(R.id.edit);
edit.clearFocus();
三 强制隐藏Android输入法窗口
EditText edit=(EditText)findViewById(R.id.edit);
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edit.getWindowToken(),0);
3. 始终不弹出软件的方法:
EditText edit=(EditText)findViewById(R.id.edit);
edit.setInputType(InputType.TYPE_NULL);
74)UI界面使用EditText时,在注册文件中对该activity添加软键盘属性:
android:windowSoftInputMode="adjustResize|stateHidden"
adjustResize: 不修改界面 stateHidden:不自动弹出
75) 善用Android预定义样式
字体大小:
"?android:attr/textAppearanceLarge","?android:attr/textAppearanceMedium" ,"?android:attr/textAppearanceSmall"
android:textAppearance="?android:attr/textAppearanceLarge" 或者
style="?android:attr/textAppearanceLarge"
字体颜色:
android:textColor="?android:attr/textColorPrimary"
android:textColor="?android:attr/textColorSecondary"
android:textColor="?android:attr/textColorTertiary"
android:textColor="?android:attr/textColorPrimaryInverse"
android:textColor="?android:attr/textColorSecondaryInverse"
分隔符:
横向:
<View android:layout_width="fill_parent"
android:layout_height="1dip"
android:background="?android:attr/listDivider" />
纵向:
<View android:layout_width="1dip"
android:layout_height="fill_parent"
android:background="?android:attr/listDivider" />
CheckBox
style="?android:attr/starStyle"
类似标题栏效果的TextView
style="?android:attr/listSeparatorTextViewStyle"
其它有用的样式
android:layout_height="?android:attr/listPreferredItemHeight"
android:paddingRight="?android:attr/scrollbarSize"
style="?android:attr/windowTitleBackgroundStyle"
style="?android:attr/windowTitleStyle"
android:layout_height="?android:attr/windowTitleSize"
android:background="?android:attr/windowBackground"
76)view的抖动效果(左右抖动)
TranslateAnimation anim = new TranslateAnimation(imageView.getWidth(),
imageView.getWidth() + 10, imageView.getHeight(), imageView.getHeight());
anim.setInterpolator(new CycleInterpolator(6f)); //循环次数
//CycleInterpolator:动画从开始到结束,变化率是循环给定次数的正弦曲线。
anim.setDuration( 500 ); //播放时间
magview.startAnimation(anim);
77)activity的切换动画②
① 从右到左 →
overridePendingTransition(R.anim.in_form_left, R.anim.out_of_right);
in_form_left:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_interpolator">
<translate
android:fromXDelta="-100%p"
android:toXDelta="0%p"
android:duration="500" />
</set>
out_of_right:
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_interpolator">
<translate
android:fromXDelta="0%p"
android:toXDelta="100%p"
android:duration="500" />
</set> ④
① 从左到右 ←
getActivity().overridePendingTransition(R.anim.in_from_right, R.anim.out_of_left);
in_from_right:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_interpolator">
<translate
android:fromXDelta="100%p"
android:toXDelta="0%p"
android:duration="500" />
</set>
out_of_left:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_interpolator">
<translate
android:fromXDelta="0%p"
android:toXDelta="-100%p"
android:duration="500" />
</set>
③ 上下切换:
out_to_up.xml (从屏幕上面退出)
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_interpolator"
android:fromYDelta="0%p"
android:toYDelta="-100%p"
android:duration="1000">
</translate>
in_from_down.xml (从屏幕下面进入)
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_interpolator"
android:fromYDelta="100%p"
android:toYDelta="0%p"
android:duration="1000">
</translate>
④
78)listView的setOnItemClickListener方法中可以控制adapter中的组件
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
View lastCheckedOption = view.findViewById(R.id.doctor_adapter_re);
lastCheckedOption.setBackgroundColor(color.gray_alarm);
}
});
79)接口回调标准代码
① 通过方法的方式
public interface OnListViewItemClik{
void setItemClick(int position);
}
public void setListViewItemClik(OnListViewItemClik onclick){
this.onclick=onclick;
}
② 通过参数分方式
private interface OnListViewItemClik{
void setItemClick(int position);
}
public BleAdapter(List<BleDevice> bleList,OnBleConnectChangeListener listener ) {
this.context=context;
this.listener=listener;
}
80)Listview 点击item项后,让item常亮
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if(((ListView)parent).getTag() != null){
((View)((ListView)parent).getTag()).setBackgroundColor(Color.TRANSPARENT);
}
((ListView)parent).setTag(view);
view.setBackgroundColor(color.gray_alarm);
}
});
81)点击组件背景白变灰色
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@color/gray_white"></item>
<item android:state_pressed="false" android:drawable="@color/white"></item>
</selector>
82)自画button,有点击效果
<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<shape android:shape="rectangle">
<solid android:color="#18c2ed"/>
<stroke android:width="1dp" android:color="#18c2ed"/>
<corners android:radius="10dp" />
<padding android:bottom="10dp" android:left="30dp" android:right="30dp" android:top="10dp"/>
</shape>
</item>
<item android:state_pressed="false">
<shape android:shape="rectangle">
<stroke android:width="1dp" android:color="#FFFFFF"/>
<corners android:radius="10dp" />
<padding android:bottom="10dp" android:left="30dp" android:right="30dp" android:top="10dp"/>
</shape>
</item>
</selector>
83)View悬浮在所有View之上:
WindowManager wm = (WindowManager) getApplicationContext()
.getSystemService(WINDOW_SERVICE);
WindowManager.LayoutParams wmParams = new WindowManager.LayoutParams();
wmParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY;
wmParams.format = 1;
wmParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL | LayoutParams.FLAG_NOT_FOCUSABLE;;
wmParams.width = 200;
wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;;
wm.addView(new Button(getApplicationContext()), wmParams); // 创建View
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
84) 获取res里图片资源的id的方法:
level++;
int resId=context.getResources().getIdentifier("v"+level, "drawable", context.getPackageName());
mVoice.setImageResource(resId);
85)将dp转换为px
mMenuRightPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50,
context.getResources().getDisplayMetrics());
86)一个TextView展示多行数据
String str=new StringBuilder()
.append("\n")
.append("说明:").append("\n")
.append("1.悬浮窗可随意移动").append("\n")
.append("2.实时显示当前内存数据").append("\n")
.append("3.上层数据表示可用内存值").append("\n")
.append("4.下层数据表示总内存值").append("\n")
.append("5.点击悬浮窗出现关闭小图标可直接关闭").append("\n").append("\n").toString();
tv.setText(str);
87)隐藏软键盘
private void hideKeyboard() {
if(imm==null){
imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
}
if(imm.isActive()){
imm.hideSoftInputFromWindow(heightEditText.getWindowToken() , 0);
}
}
有EditText的activity都要加这句话
android:windowSoftInputMode="adjustUnspecified|stateHidden"
88)ToggleButton开关按钮的使用
<style name="setting_toggle_button" parent="android:style/Theme">
<item name="android:layout_width">60dp</item>
<item name="android:layout_height">32dp</item>
<item name="android:layout_centerVertical">true</item>
<item name="android:layout_alignParentRight">true</item>
<item name="android:textOn">""</item>
<item name="android:textOff">""</item>
<item name="android:background">@drawable/setting_toggle_bg_sel</item>
<item name="android:clickable">false</item>
</style>
setting_toggle_bg_sel.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/setting_item_unselected" android:state_checked="false"/>
<item android:drawable="@drawable/setting_item_selected" android:state_checked="true"/>
</selector>
fitlerBWToggle.setChecked(value);
89) ObjectAnimator 创建动画
/*
* 执行一个动画
*/
public void animClick(View v){
ObjectAnimator objAnimator=ObjectAnimator.ofFloat(imageView, "translationX", 0,100);
objAnimator.setDuration(2000);
objAnimator.setRepeatCount(10);
objAnimator.setInterpolator(new LinearInterpolator());
objAnimator.start();
}
/**
* 两个动画同时执行
*/
public void animClick(View v){
ObjectAnimator anim1 = ObjectAnimator.ofFloat(imageView, "scaleX",
1.0f, 2f);
ObjectAnimator anim2=ObjectAnimator.ofFloat(imageView, "alpha", 1f,0f);
AnimatorSet animSet = new AnimatorSet();
animSet.setDuration(2000);
animSet.setInterpolator(new LinearInterpolator());
//两个动画同时执行
animSet.playTogether(anim1, anim2);
animSet.start();
}
/**
* anim1,anim2,anim3同时执行
* anim4接着执行
*/
public void animClick(View v){
float cx = imageView.getX();
ObjectAnimator anim1 = ObjectAnimator.ofFloat(imageView, "scaleX",1.0f, 2f);
ObjectAnimator anim2 = ObjectAnimator.ofFloat(imageView, "scaleY",1.0f, 2f);
ObjectAnimator anim3 = ObjectAnimator.ofFloat(imageView, "x", cx , 0f);
ObjectAnimator anim4 = ObjectAnimator.ofFloat(imageView,"translationX", 0,360f);
AnimatorSet animSet = new AnimatorSet();
animSet.play(anim1).with(anim2);
animSet.play(anim2).with(anim3);
animSet.play(anim4).after(anim3);
animSet.setDuration(1000);
animSet.start();
}
90)开机自启动
开机后系统会发送一个启动完毕的广播,Intent.ACTION_BOOT_COMPLETED,
那么我们只需要自定义一个BroadcastReciever接收这个广播,在接收到广播后启动我们的程序就可以实现开机启动了。
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
// 是否选择了开机启动
boolean start = PreferenceManager.getDefaultSharedPreferences(
context).getBoolean(
CleanerActivity.KEY_START_WHEN_BOOT_COMPLETED, true);
if (start) {
Intent i = new Intent();
i.setClass(context, FloatService.class);
context.startService(i);
}
}
}
}
AndroidManifest.xml中的声明如下:
<receiver android:name="MyBroadcastReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
91)EditText inputType说明
android:inputType="textCapWords"//单词首字母大小
android:inputType="textCapSentences"//仅第一个字母大小
android:inputType="textAutoCorrect"android:inputType="textAutoComplete"//前两个自动完成
android:inputType="textMultiLine"//多行输入
android:inputType="textImeMultiLine"//输入法多行(不一定支持)
android:inputType="textNoSuggestions"//不提示
android:inputType="textUri"//URI格式
android:inputType="textEmailAddress"//电子邮件地址格式
android:inputType="textEmailSubject"//邮件主题格式
android:inputType="textShortMessage"//短消息格式
android:inputType="textLongMessage"android:inputType="textPersonName"//人名格式
android:inputType="textPostalAddress"//邮政格式
android:inputType="textPassword"//密码格式
android:inputType="textVisiblePassword"//密码可见格式
android:inputType="textWebEditText"//作为网页表单的文本格式
android:inputType="textFilter"//文本筛选格式
android:inputType="textPhonetic"//拼音输入格式
android:inputType="number"//数字格式
android:inputType="numberSigned"//有符号数字格式
android:inputType="numberDecimal"//可以带小数点的浮点格式
android:inputType="phone"//拨号键盘
android:inputType="datetime"android:inputType="date"//日期键盘
android:inputType="time"//时间键盘
92)dip,px转换
public static int dip2px(Context context, float dipValue){
final float scale = context.getResources().getDisplayMetrics().density;
return (int)(dipValue * scale + 0.5f);
}
public static int px2dip(Context context, float pxValue){
final float scale = context.getResource().getDisplayMetrics().density;
return (int)(pxValue / scale + 0.5f);
}
93)适配
public static int getPhoneDpi(Context context){
WindowManager wm = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics dm = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(dm);
int densityDPI = dm.densityDpi;
return densityDPI;
}
int dip = DensityUtil.getPhoneDpi(context);
if (dip >= 480) { //dip是每英寸像素点(分为120低,160中,240高,320超高,480苹果分辨率)
canvas.drawText(infoRect.top + 100, textPaint);
} else {
canvas.drawText(infoRect.top + 60, textPaint);
}
94) 动态添加布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<FrameLayout
android:id="@+id/frameLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</FrameLayout>
</LinearLayout>
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FrameLayout fl=(FrameLayout)findViewById(R.id.frameLayout);
fl.addView(new MyView(this));
}
95) 获取网络连接模式
public class NetUtil {
public static final int NETWORN_NONE = 0;
public static final int NETWORN_WIFI = 1;
public static final int NETWORN_MOBILE = 2;
public static int getNetworkState(Context context) {
ConnectivityManager connManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
// Wifi
State state = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
.getState();
if (state == State.CONNECTED || state == State.CONNECTING) {
return NETWORN_WIFI;
}
// 3G
state = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
.getState();
if (state == State.CONNECTED || state == State.CONNECTING) {
return NETWORN_MOBILE;
}
return NETWORN_NONE;
}
}
96)反射方法获取状态栏高度
public static int getStatusBarHeight(Context context) {
int statusBarHeight = 20;
try {
Class<?> _class = Class.forName("com.android.internal.R$dimen");
Object object = _class.newInstance();
Field field = _class.getField("status_bar_height");
int restult = Integer.parseInt(field.get(object).toString());
statusBarHeight = context.getResources().getDimensionPixelSize(
restult);
} catch (Exception e) {
e.printStackTrace();
}
// Toast.makeText(getActivity(), "StatusBarHeight = " + statusBarHeight,
// Toast.LENGTH_SHORT).show();
return statusBarHeight;
}
97)每隔一秒钟向主线程发送数据
mTimer = new Timer();
mTimer.schedule(new TimerTask() {
@Override
public void run() {
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}
}, 1000, 1000); /* 表示1000毫秒之後,每隔1000毫秒執行一次 */
private Handler handler = new Handler() {
private int progress=0;
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
int msgId = msg.what;
switch (msgId) {
case 1:
progress++;
if(progress==10){
mTimer.cancel();
}
break;
}
}
};
98)剪切(Clip)图像资源
剪切图像资源可以只显示一部分图像,这种资源经常被用在进度条的制作上。剪切图像资源是一个XML格式文件,资源只包含一个<clip>标签
res/drawable/clip.xml
<?xml version="1.0" encoding="utf-8"?>
<clip xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/progress" android:clipOrientation="horizontal"
android:gravity="left" />
<ImageView
android:id="@+id/image"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/clip"/>
ImageView imageview = (ImageView) findViewById(R.id.image);
ClipDrawable drawable = (ClipDrawable) imageview.getBackground();
drawable.setLevel(3000) level的范围为[0,10000]
99)常用的一些系统属性
字体大小:
style="?android:attr/textAppearanceLarge"
style="?android:attr/textAppearanceMedium"
style="?android:attr/textAppearanceSmall"
字体颜色:
android:textColor="?android:attr/textColorPrimary"
android:textColor="?android:attr/textColorSecondary"
android:textColor="?android:attr/textColorTertiary"
android:textColor="?android:attr/textColorPrimaryInverse"
android:textColor="?android:attr/textColorSecondaryInverse"
分隔符 横向:
<View
android:layout_width="fill_parent"
android:layout_height="1dip"
android:background="?android:attr/listDivider" />
100)如果sd卡存在就创建目录,如果没有就将目录创建在缓存
public static String getCurrentDataPath(Context context, String folderName) throws IOException {
String currentDataPath = "";
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
currentDataPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + folderName;
File dir = new File(currentDataPath);
if (!dir.exists())
dir.mkdir();
} else {
currentDataPath = context.getFilesDir().getAbsolutePath();
}
return currentDataPath;
}