android开发常用代码(经常更新)
2015-03-03 10:35
169 查看
android开发中我们需要一些代码来使我们的界面更美观,控件更漂亮。
除了android开发,还有程序中经常用到的东西。
比如圆角的button啊,view的布局啊等等。
下面是一些常用的代码
1.圆角button
android开发中我们需要一些代码来使我们的界面更美观,控件更漂亮。
比如圆角的button啊,view的布局啊等等。比如圆角的button啊,view的布局啊等等。
下面是一些常用的代码下面是一些常用的代码
1.圆角button1.圆角button
<?xml version="1.0" encoding="UTF-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <!-- 填充的颜色 --> <solid android:color="#3881fe" /> <!-- 设置按钮的四个角为弧形 --> <!-- android:radius 弧形的半径 --> <corners android:radius="5dip" /> <!-- padding:Button里面的文字与Button边界的间隔 --> <padding android:left="10dp" android:top="10dp" android:right="10dp" android:bottom="10dp" /> </shape>
2.canvas画圆角矩形
RectF backRect = new RectF(1, 0, (float) (getWidth() - 1), getHeight() - 4.5f); canvas.drawRoundRect(backRect, 7, 7, mPaint);
3.popupWindow使用
public void showPopupWindow(Context context, View parent) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); final View view = inflater.inflate(R.layout.popwindow, null, false); int screenWidth = getResources().getDisplayMetrics().widthPixels; final PopupWindow pw = new PopupWindow(view, screenWidth - 50, 300, true); pw.setFocusable(true); pw.setTouchable(true); //点击popupwindow以外区域消失 pw.setBackgroundDrawable(new BitmapDrawable()); pw.setOutsideTouchable(true); pw.showAtLocation(MainActivity.this.findViewById(R.id.main), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); // 显示popupWindow对话框 }
4.LayoutInflater 的使用
LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); final View view = inflater.inflate(R.layout.xxxx, null, false);
5.生成圆角图片
public static Bitmap GetRoundedCornerBitmap(Bitmap bitmap) { try { Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888); Canvas canvas = new Canvas(output); final Paint paint = new Paint(); final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); final RectF rectF = new RectF(new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight())); final float roundPx = 14; paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(Color.BLACK); canvas.drawRoundRect(rectF, roundPx, roundPx, paint); paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); final Rect src = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); canvas.drawBitmap(bitmap, src, rect, paint); return output; } catch (Exception e) { return bitmap; } }
6.得到SD路径
public static String getSDPath() { File SDPath = null; boolean isSDExist = Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED); if (isSDExist == true) { SDPath = Environment.getExternalStorageDirectory(); } return SDPath.toString(); }
7.将string写到文件末尾
/** * 将字符串写到文件末尾 * @param txt 原始字符串 * @param fileName 带路径的文件名 * @return true 写入成功 */ public static boolean stringToFileEnd(String txt, String fileName) { File file = new File(fileName); if (file.exists()) { try { FileOutputStream outputStream = new FileOutputStream(fileName, true); outputStream.write(txt.getBytes()); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } return true; } else { return false; } }
8.得到手机屏幕高度宽度以及scale
scale = getResources().getDisplayMetrics().density; screenHeight = getResources().getDisplayMetrics().heightPixels; screenWidth = getResources().getDisplayMetrics().widthPixels;
9.onMeasure常用方法 获取当前控件高度和宽度等等
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { height = screenHeight / 4; width = measureWidth(widthMeasureSpec); setMeasuredDimension(width, height); } private int measureHeight(int measureSpec) { int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); // Default size if no limits are specified. int result = 500; if (specMode == MeasureSpec.AT_MOST) { // Calculate the ideal size of your // control within this maximum size. // If your control fills the available // space return the outer bound. result = specSize; } else if (specMode == MeasureSpec.EXACTLY) { // If your control can fit within these bounds return that value. result = specSize; } return result; } private int measureWidth(int measureSpec) { int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); // Default size if no limits are specified. int result = 500; if (specMode == MeasureSpec.AT_MOST) { // Calculate the ideal size of your control // within this maximum size. // If your control fills the available space // return the outer bound. result = specSize; } else if (specMode == MeasureSpec.EXACTLY) { // If your control can fit within these bounds return that value. result = specSize; } return result; }
10.bitmap的缩放
/** * 按照指定长宽压缩 * * @param srcBitmap * @param newWidth * @param newHeight * @return */ public static Bitmap bitmapZoomBySize(Bitmap srcBitmap, int newWidth, int newHeight) { int srcWidth = srcBitmap.getWidth(); int srcHeight = srcBitmap.getHeight(); float scaleWidth = ((float) newWidth) / srcWidth; float scaleHeight = ((float) newHeight) / srcHeight; return bitmapZoomByScale(srcBitmap, scaleWidth, scaleHeight); } /** * 使用长宽缩放比缩放 * * @param srcBitmap * @param scaleWidth * @param scaleHeight * @return */ public static Bitmap bitmapZoomByScale(Bitmap srcBitmap, float scaleWidth, float scaleHeight) { int srcWidth = srcBitmap.getWidth(); int srcHeight = srcBitmap.getHeight(); Matrix matrix = new Matrix(); matrix.postScale(scaleWidth, scaleHeight); Bitmap resizedBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, srcWidth, srcHeight, matrix, true); if (resizedBitmap != null) { return resizedBitmap; } else { return srcBitmap; } }
11.文件读写相关操作
//判断文件是否存在 public boolean isFileExits(String fileName) { File file = new File(SDPath + fileName); return file.exists(); } //新建文件夹 public void makeDir(String dirName) { File file = new File(SDPath + dirName); if (!file.exists()) file.mkdir(); } //获得文件数量 public int getNumOfFiles(String dir) { File file = new File(SDPath + dir); File[] numFile = file.listFiles(); return numFile.length; }
//删除一个文件
<span style="white-space:pre"> </span>public boolean deleteFile(String fileName) { File file = new File(SDPath + fileName); if (file.exists()) { System.out.println("file name is " + file.getName()); try { file.delete(); } catch (Exception e) { e.printStackTrace(); } return true; } else { return false; } } //读取一个文件 public String readFromFile(String fileName) { String res = ""; try { FileInputStream inputStream = new FileInputStream(SDPath + fileName); int len = inputStream.available(); byte buffer[] = new byte[len]; inputStream.read(buffer); res = EncodingUtils.getString(buffer, "UTF-8"); inputStream.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println("res ----->" + res); return res; } //将字符串写到文件末尾 public boolean stringToFileEnd(String txt,String fileName) { File file = new File(SDPath + fileName); if (file.exists()) { try { FileOutputStream outputStream = new FileOutputStream(SDPath + fileName,true); outputStream.write(txt.getBytes()); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } return true; } else { return false; } } //将字符串从文件头部开始写 public boolean stringToFile(String txtString,String fileName) { File file = new File(SDPath + fileName); if (file.exists()) { try { FileOutputStream outputStream = new FileOutputStream(SDPath + fileName); outputStream.write(txtString.getBytes()); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } return true; } else { return false; } } //删除文件 public File createFile(String fileName) { File file = new File(SDPath + fileName); try { file.createNewFile(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return file; }
返回事件捕捉
public void onBackPressed() { // TODO Auto-generated method stub System.out.println("hehehehhehehehhe"); super.onBackPressed(); }
获取当前时间:
Time t=new Time("GMT+8"); // or Time t=new Time("GMT+8"); 加上Time Zone资料。 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;
唯一不足的是月份少一月,小时得加8
22.获取星期几
public class DateString { private static String mYear; private static String mMonth; private static String mDay; private static String mWay; public static String StringDate(){ final Calendar c = Calendar.getInstance(); c.setTimeZone(TimeZone.getTimeZone("GMT+8:00")); mYear = String.valueOf(c.get(Calendar.YEAR)); // 获取当前年份 mMonth = String.valueOf(c.get(Calendar.MONTH) + 1);// 获取当前月份 mDay = String.valueOf(c.get(Calendar.DAY_OF_MONTH));// 获取当前月份的日期号码 mWay = String.valueOf(c.get(Calendar.DAY_OF_WEEK)); if("1".equals(mWay)){ mWay ="SUN"; }else if("2".equals(mWay)){ mWay ="MON"; }else if("3".equals(mWay)){ mWay ="TUE"; }else if("4".equals(mWay)){ mWay ="WED"; }else if("5".equals(mWay)){ mWay ="THU"; }else if("6".equals(mWay)){ mWay ="FRI"; }else if("7".equals(mWay)){ mWay ="SAT"; } return mYear + "年" + mMonth + "月" + mDay+"日"+"/星期"+mWay; } }
22.判断当前是否联网
public boolean inNetwork() { ConnectivityManager cManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = cManager.getActiveNetworkInfo(); if (info != null && info.isAvailable()) { // do something // 能联网 return true; } else { // do something // 不能联网 return false; } }
23.listview一些常用属性设置
去掉item分割线 android:divider="@null" 去掉顶部和底部边缘模糊 android:overScrollMode="never" 去掉滑动栏 android:scrollbars="none"
hashmap遍历
public static void printHash(HashMap<String, String> hashMap) { Iterator iter = hashMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); Object key = entry.getKey(); Object val = entry.getValue(); System.out.println("key = " + key + " val = " + val); } }
解析json字符串
private static Map<String, String> parseJSONString(String JSONString) throws JSONException { Map<String, String> resultMap = new HashMap<String, String>(); JSONArray jsonArray = new JSONArray(); try { // 直接把JSON字符串转化为一个JSONObject对象 JSONObject person = new JSONObject(JSONString); System.out.println("the info is " + person.getJSONArray("infoBaseTime").toString()); jsonArray = person.getJSONArray("infoBaseTime"); } catch (JSONException e) { e.printStackTrace(); } for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); Map<String, String> map = new HashMap<String, String>(); for (Iterator<?> iter = jsonObject.keys(); iter.hasNext();) { String key = (String) iter.next(); String value = jsonObject.get(key).toString(); resultMap.put(key, value); System.out.println("key is " + key + " value is " + value); } // rsList.add(map); } printHash(resultMap); return resultMap; }
http发起网络请求
/** * 想数据库写入手机参数 * * @param IMEI * 手机的IMEI * @param basetime * 手机滑动基数 * @param deviceID * 手机设备号 * @throws IOException */ public static void PostBaseTime(String IMEI, float basetime, String deviceID) throws IOException { String responseRes = ""; HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(HTTP_POST_BASETIME); List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>(); formparams.add(new BasicNameValuePair("baseTime", basetime + "")); formparams.add(new BasicNameValuePair("IMEI", IMEI)); formparams.add(new BasicNameValuePair("deviceID", deviceID)); UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, HTTP.UTF_8); httpPost.setEntity(uefEntity); HttpResponse response = (HttpResponse) httpClient.execute(httpPost); if (response.getStatusLine().getStatusCode() == 200) { responseRes = EntityUtils .toString(response.getEntity(), HTTP.UTF_8); System.out.println("the res is " + responseRes); } }
得到手机一些参数,屏幕大小等等
screenWidth = wm.getDefaultDisplay().getWidth(); screenheight = wm.getDefaultDisplay().getHeight(); System.out.println("screen width is " + screenWidth + " screen height is " + screenheight); scale = getActivity().getResources().getDisplayMetrics().density; topHeight = (int) (scale * 50 + 0.5f); bottomHeight = (int) (scale * 55 + 0.5f); notiHeight = Resources.getSystem().getDimensionPixelSize( Resources.getSystem().getIdentifier("status_bar_height", "dimen", "android"));
相关文章推荐
- android 开发中常用到的一些代码片段(一)
- [IOS]iphone开发之常用代码:不断更新
- Android 开发常用代码片段
- Android 开发常用代码片段
- Android 开发常用代码片段
- 开发中常用代码片段汇总(持续更新)
- iphone开发之常用代码:不断更新
- Android 开发常用代码
- iphone开发常用代码(不断更新)
- Android 开发常用代码片段
- android 笔记 --- Android中开发中常用代码
- Android开发之常用代码片段
- Android开发常用代码
- Android 开发常用代码片段
- android 开发中常用到的一些代码片段(一)
- 【引用】iphone开发常用代码(不断更新)
- android 开发中常用到的一些代码片段(一)
- android - 常用知识点以及代码片段(不断更新)
- android 开发中遇到的ERROR经常长期更新笔记
- Android-开发常用代码汇总