android开发常用代码(经常更新)
来源:互联网 发布:lol30级号淘宝 编辑:程序博客网 时间:2024/06/06 02:38
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对话框}
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 exceptione.printStackTrace();}return file;}
返回事件捕捉
public void onBackPressed() {// TODO Auto-generated method stubSystem.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 拷贝assets目录下所有文件及文件夹到指定路径
- public class AssetsCopyer {
- private static final String TAG = "AssetsCopyer";
- public static void releaseAssets(Context context, String assetsDir,
- String releaseDir) {
- // Log.d(TAG, "context: " + context + ", " + assetsDir);
- if (TextUtils.isEmpty(releaseDir)) {
- return;
- } else if (releaseDir.endsWith("/")) {
- releaseDir = releaseDir.substring(0, releaseDir.length() - 1);
- }
- if (TextUtils.isEmpty(assetsDir) || assetsDir.equals("/")) {
- assetsDir = "";
- } else if (assetsDir.endsWith("/")) {
- assetsDir = assetsDir.substring(0, assetsDir.length() - 1);
- }
- AssetManager assets = context.getAssets();
- try {
- String[] fileNames = assets.list(assetsDir);//只能获取到文件(夹)名,所以还得判断是文件夹还是文件
- if (fileNames.length > 0) {// is dir
- for (String name : fileNames) {
- if (!TextUtils.isEmpty(assetsDir)) {
- name = assetsDir + File.separator + name;//补全assets资源路径
- }
- // Log.i(, brian name= + name);
- String[] childNames = assets.list(name);//判断是文件还是文件夹
- if (!TextUtils.isEmpty(name) && childNames.length > 0) {
- checkFolderExists(releaseDir + File.separator + name);
- releaseAssets(context, name, releaseDir);//递归, 因为资源都是带着全路径,
- //所以不需要在递归是设置目标文件夹的路径
- } else {
- InputStream is = assets.open(name);
- // FileUtil.writeFile(releaseDir + File.separator + name, is);
- writeFile(releaseDir + File.separator + name, is);
- }
- }
- } else {// is file
- InputStream is = assets.open(assetsDir);
- // 写入文件前, 需要提前级联创建好路径, 下面有代码贴出
- // FileUtil.writeFile(releaseDir + File.separator + assetsDir, is);
- writeFile(releaseDir + File.separator + assetsDir, is);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- private static boolean writeFile(String fileName, InputStream in) throws IOException
- {
- boolean bRet = true;
- try {
- OutputStream os = new FileOutputStream(fileName);
- byte[] buffer = new byte[4112];
- int read;
- while((read = in.read(buffer)) != -1)
- {
- os.write(buffer, 0, read);
- }
- in.close();
- in = null;
- os.flush();
- os.close();
- os = null;
- // Log.v(TAG, "copyed file: " + fileName);
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- bRet = false;
- }
- return bRet;
- }
- private static void checkFolderExists(String path)
- {
- File file = new File(path);
- if((file.exists() && !file.isDirectory()) || !file.exists())
- {
- file.mkdirs();
- }
- }
- }
0 0
- android开发常用代码(经常更新)
- android 开发中遇到的ERROR经常长期更新笔记
- leetcode习题代码(经常更新)
- Android开发常用代码
- Android 开发常用代码
- iOS开发常用代码【持续更新中】
- Android开发中经常会用到的功能代码
- Android开发中经常用到的代码模块
- 常用正则式整理(经常更新)
- android开发常用代码片段
- Android 开发常用代码片段
- Android 开发常用代码片段
- Android 开发常用代码片段
- Android-开发常用代码汇总
- Android 开发常用代码片段
- Android开发 常用代码片段
- Android 开发常用代码片段
- Android 开发常用代码片段
- ArcEngine数据编辑操作--添加线
- 砝码分块全称重问题
- Linux下JDK和Tomcat安装
- C# 中GUID生成格式的四种格式
- android 横竖屏切换属性和播放视频全屏切换
- android开发常用代码(经常更新)
- mysql 5.6 status 分类
- UBUNTU 12.04下编译安装 GCC4.1.2
- CRC从原理到实现
- 2.3.1 向索引添加文档例程
- 1001. A+B Format (20)
- apache启用gzip压缩方法
- ArcEngine数据编辑操作--通过线创建面
- Managing Your App's Memory(Android App内存管理)