1. Android之Context和Activity互相轉(zhuǎn)換
<1>、context轉(zhuǎn)換為activity
Activity activity = (Activity) context;
<2>、從activity得到context
//在activity的方法中用context = getBaseContext();
//而在activity中用context = this即可. ,因為Activity的父類是Context
2. 日期格式化 相互轉(zhuǎn)換
- 日期轉(zhuǎn)字符串
Calendar canlendarNow=Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String str = sdf.format(canlendarNow);
Log.e("Tiger:", str);
- 字符串轉(zhuǎn)日期
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-mm-dd");
try {
Date date= sdf.parse("2018-08-08");
String strDate= sdf.format(date);
Log.e("Tiger:", strDate);
3. 動態(tài)設(shè)置 Margins
? -2表示 LinearLayout.LayoutParams.WRAP_CONTENT
LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(-2,-2);
lp.setMargins(10,10,10,10);
view.setLayoutParams(lp);
4. 遍歷Map集合
Set<String> sets= maps.keySet();
for(String key:sets){
System.out.println(key+":"+maps.get(key);
}
for(Map.Entry<String,String> item:maps.entrySet()){
System.out.println(item.getKey()+":"+item.getValue());
}
5. 設(shè)置Drawable圖片大小
int[] textviews = {R.id.tvHome, R.id.tvSchedule,R.id.tvData,R.id.tvRanking,R.id.tvGallery};
for (int i : textviews) {
TextView textView = (TextView) findViewById(i);
//會獲取到四張圖片分別為 左上右下
Drawable[] drawables = textView.getCompoundDrawables();
//參數(shù)說明:距左邊距離,距右邊距離,長寬
drawables[1].setBounds(5, 5, 100, 100);
//沒有圖片設(shè)置為null
textView.setCompoundDrawables(null, drawables[1], null, null);
}
6. Glide 解析圖片
Glide.with(MainActivity.this).load(Base64.decode(base64字符串, Base64.DEFAULT)).into(imageView);
- **不緩存圖片 **
.load(Glide.TRIM_MEMORY_MODERATE)
7.ListView不顯示點擊效果及分割線
android:listSelector="@android:color/transparent"
android:divider="@null"
8. 任何類型轉(zhuǎn)字符串
String.valueof()
9.Base64 字符串與Bitmap 之間的相互轉(zhuǎn)換
/**
* 將Bitmap轉(zhuǎn)換成base64字符串
* @param bitmap
* @return
*/
public static String bitmaptoBase64(Bitmap bitmap) {
String result = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
baos.flush();
baos.close();
byte[] bytes = baos.toByteArray();
result = Base64.encodeToString(bytes, Base64.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* 將base64字符串轉(zhuǎn)換為Bitmap
* @param base64String
* @return
*/
public Bitmap base64ToBitmap(String base64String){
byte[] bytes=Base64.decode(base64String,Base64.DEFAULT);
Bitmap bitmap=BitmapFactory.decodeByteArray(bytes,0,bytes.length);
return bitmap;
}
10.讀取InputStream 中的內(nèi)容
/**
* 讀取 InputStream 到 String字符串中
*/
public static String readStream(InputStream in) {
try {
//<1>創(chuàng)建字節(jié)數(shù)組輸出流,用來輸出讀取到的內(nèi)容
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//<2>創(chuàng)建緩存大小
byte[] buffer = new byte[1024]; // 1KB
//每次讀取到內(nèi)容的長度
int len = -1;
//<3>開始讀取輸入流中的內(nèi)容
while ((len = in.read(buffer)) != -1) { //當?shù)扔?1說明沒有數(shù)據(jù)可以讀取了
baos.write(buffer, 0, len); //把讀取到的內(nèi)容寫到輸出流中
}
//<4> 把字節(jié)數(shù)組轉(zhuǎn)換為字符串
String content = baos.toString();
//<5>關(guān)閉輸入流和輸出流
in.close();
baos.close();
//<6>返回字符串結(jié)果
return content;
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
}
public static String readStream2(InputStream in) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb_response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb_response.append(line);
}
in.close();
return sb_response.toString();
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
11.延遲執(zhí)行
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
// 對應(yīng)操作
}
},5000);
12. Java 占位符拼接字符串
MessageFormat.format("My name is {0}. I am {1} year old .",name,age);
13.讀取資源文件
raw 文件夾下資源會直接打進 APK文件中
-
讀取res/raw 下的文件資源,可以通過一下方式來獲取輸入流
InputStream is = getResources().openRawResource(R.raw.filename); 通過 URI訪問 raw資源
Uri.parse("android.resource://" + this.getActivity().getPackageName()+ "/"+R.raw.teaser);
assets 注意assets 文件夾放在 main文件夾下,文件名帶后綴
InputStream inputStream= getAssets().open("filename.txt");
raw 和 assets 區(qū)別:
raw 可以通過 R.raw.filename來使用,assets不可以, assets 中可以放文件夾,raw不可以
14.Selector
15.顏色
透明: #00000000
半透明: #e0000000
通過代碼設(shè)置:
View v = findViewById(R.id.content);//找到你要設(shè)透明背景的layout 的id
v.getBackground().setAlpha(100);//0~255透明度值
16.設(shè)置壁紙 WallpaperManager
首先添加權(quán)限
<uses-permission android:name="android.permission.SET_WALLPAPER"/>
WallpaperManager manager = WallpaperManager.getInstance(mContext);
manager.setStream(inpustStream); //通過數(shù)據(jù)流設(shè)置壁紙
//manager.setBitmap(); //通過Bitmap 設(shè)置壁紙
//manager.clear(); //清除壁紙設(shè)置為默認壁紙
17.圖片選擇器
啟動選擇器:
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent,1);
獲取選中圖片:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode){
case 1:
if(resultCode== Activity.RESULT_OK){
if(data!=null)
{
Uri uri=data.getData();
iv.setImageURI(uri); //圖片顯示到ImageView中
InputStream inputStream=getContentResolver().openInputStream(uri); //根據(jù)uri 得到InputStream
//inputStream.available(); //inputStream 大小
}
}
break;
}
}
18.創(chuàng)建資源ID
String.xml 文件中添加
<item name="tag_id" type="id"></item>
<item name="tag_type" type="id"></item>
19.打開關(guān)閉軟鍵盤
/**
* 打卡軟鍵盤
*
* @param mEditText 輸入框
* @param mContext 上下文
*/
public static void openKeybord(final EditText mEditText, final Context mContext) {
InputMethodManager imm = (InputMethodManager) mContext
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
InputMethodManager.HIDE_IMPLICIT_ONLY);
}
/**
* 關(guān)閉軟鍵盤
*
* @param mEditText 輸入框
* @param mContext 上下文
*/
public static void closeKeybord(EditText mEditText, Context mContext) {
InputMethodManager imm = (InputMethodManager) mContext
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
}
20. 獲取ImageView的Bitmap圖片
首先需要開啟緩存:
imageView.setDrawingCacheEnabled(true); //開啟緩存
獲取圖片:
Bitmap bitmap=ivHeader.getDrawingCache();
21.Navigation 隱藏某個菜單列表
MenuItem menuItem =navigationView.getMenu().findItem(R.id.menu_id);
menuItem.setVisiable(false);