這份是我工作以來,總結的小知識庫,有些知識點現在看來太LOW了,把還覺得有用的分享出來!
Genymotion下載虛擬映象Connection timeout
Add new device出現的問題:
Failed to deploy virtual device.
Unable to create virtual device.Connection timeout occurred.
解決方案:
- 當選擇Google Nexus 5 – 6.0.0 – API 23 – 1080×1920下載device失敗後,到C:Users使用者主目錄AppDataLocalGenymobileGenymotionova下看到genymotion_vbox86p_6.0_160114_090449.ova,大小卻是0KB,在C:Users使用者主目錄AppDataLocalGenymobilegenymotion.log,開啟該檔案,找到類似“http://files2.genymotion.com/dists/6.0.0/ova/genymotion_vbox86p_6.0_160114_090449.ova”路徑,即您想要下載的映象檔案URL;
- 用迅雷去下載,下載完成後放到C:Users使用者主目錄AppDataLocalGenymobileGenymotionova;
- 重新點選Google Nexus 5 – 6.0.0 – API 23 – 1080×1920去下載,驗證安裝後即會顯示在裝置列表中。
Android Studio 如何Debug
單擊F5(Step Over),單行一個個方法執行
單擊F6(Step Into),單行執行
單擊F7(Step Out),不往下執行,回到上一行
單擊F8(Resume Program),跳出當前斷點
Android Studio設定預設的簽名檔案
新浪微博SSO登入,微信分享這些都需要簽名打包,才能看到效果,設定預設簽名檔案為自己的簽名jks,這樣就不需要打包了。
在app目錄下新增你的.jks,然後app的build.gradle檔案中的增加以下內容:
第一種:
1 2 3 4 5 6 7 8 9 10 |
android { signingConfigs { debug { storeFile file("你的.jks") storePassword 'android' keyAlias 'android' keyPassword 'android' } } } |
第二種:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
android { signingConfigs { release { storeFile file("你的.jks") storePassword 'android' keyAlias 'android' keyPassword 'android' } } buildTypes { debug { signingConfig signingConfigs.release } } } |
這樣編譯出來的debug版本直接用的是你的正式簽名
Fragment懶載入
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 |
protected boolean isVisible; @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (getUserVisibleHint()) { isVisible = true; onVisible(); } else { isVisible = false; onInvisible(); } } protected void onVisible() { lazyLoad(); } protected void lazyLoad() { if (!isVisible) { return; } getData(); } protected void onInvisible() { } |
Android studio頭註釋和方法註釋
File | Settings | Editor|File and Code Templates|Includes|File Header
1 2 3 |
/** * Created by ${USER} on ${DATE}. */ |
輸入我們想要設定的註釋模板
adapter.getPositionForSelection()和getSectionForPosition()
getPositionForSection()根據分類列的索引號獲得該序列的首個位置
getSectionForPosition()通過該項的位置,獲得所在分類組的索引號
getResources().getColor(R.color.color_name) is deprecated和drawableTop
1 2 3 |
textView.setTextColor(Color.parseColor("#FFFFFF")); //或者 ContextCompat.getColor(context, R.color.color_name) |
showPopupWindow
1 2 3 4 5 6 7 8 9 10 11 12 13 |
private void showPopupMenu(View v) { final View bgView = View.inflate(DemoApplication.getContext(), R.layout.demo_popup_window_bg, null); bgView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { hidePopupWindow(); } }); if (mPopupBackground == null) { mPopupBackground = new PopupWindow(bgView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); } mPopupBackground.showAtLocation(v, Gravity.BOTTOM, 0, 0); } |
v:父佈局
demo_popup_window_bg.xml
1 2 3 4 5 6 7 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/aliwx_common_alpha_black"> </LinearLayout> |
onFinishInflate()
view的onFinishInflate()何時呼叫的?
當View中所有的子控制元件均被對映成xml後觸發;
MyView mv = (MyView)View.inflate (context,R.layout.my_view,null);
當載入完成xml後,就會執行那個方法;
我們一般使用View的流程是在onCreate中使用setContentView來設定要顯示Layout檔案或直接建立一個View,在當設定了ContentView之後系統會對這個View進行解析,然後回撥當前檢視View中的onFinishInflate方法。只有解析了這個View我們才能在這個View容器中獲取到擁有Id的元件,同樣因為系統解析完View之後才會呼叫onFinishInflate方法,所以我們自定義元件時可以onFinishInflate方法中獲取指定子View的引用。
Fragment設定隱藏或顯示某個Fragment
MainFragment點選
1 2 3 4 5 6 |
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { ((MainActivity) getActivity()).showImageFragment(true, mData.get(position).get("title").toString(), mData.get(position).get("imgUrl").toString()); } |
MainActivity
1 2 3 4 5 6 7 8 9 10 11 12 |
public void showImageFragment(boolean show, String imgTxt, String imgUrl) { // showActionbarWithTabs(!show); if (show) { getSupportFragmentManager().beginTransaction() .show(imageDetailFragment).commit(); imageDetailFragment.setImgData(imgTxt, imgUrl); } else { getSupportFragmentManager().beginTransaction() .hide(imageDetailFragment).commit(); } } |
獲取arrt的值
不同主題下需要把顏色,數值寫成attr屬性
xml裡,我們可以簡單的引用attr屬性值
1 |
android:background="?attr/colorPrimary" |
程式碼獲取
1 2 3 |
TypedValue typedValue = new TypedValue(); mContext.getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true); int colorPrimary = typedValue.data;//value.data裡面儲存著的就是獲取到的colorPrimary的值 |
撥號盤撥打電話
1 2 3 4 5 |
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "400-036-1977")); // intent.setAction(Intent.ACTION_CALL);// 直接撥號 intent.setAction(Intent.ACTION_DIAL);// 撥號盤 startActivity(intent); |
Drawable /Bitmap、String/InputStream、Bitmap/byte[]互轉
http://wuxiaolong.me/2015/08/10/Drawable-to-Bitmap/
ProgressDialog
1 2 3 4 5 |
final ProgressDialog progress = new ProgressDialog(LoginActivity.this); progress.setMessage("請稍等..."); progress.setCanceledOnTouchOutside(false); progress.show(); progress.dismiss(); |
毫秒
毫秒Calendar.getInstance().getTimeInMillis()和System.currentTimeMillis()
Fragment setUserVisibleHint(boolean isVisibleToUser)
1 2 3 4 5 6 7 8 9 |
@Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (isVisibleToUser) { //相當於Fragment的onResume } else { //相當於Fragment的onPause } } |
Fragment onActivityResult
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); getActivity(); if (resultCode == Activity.RESULT_OK && requestCode == AppUtils.REQUEST_CODE_ISLOGIN) { // 檢查是否完善資料 if (AppUtils.getSharedPreferences(getActivity()).getBoolean( "hasPersonalData", false)) { // 取本地存取是否完善資料,完善直接提示諮詢對話方塊 consultationDialog(); } else { getCheckPersonalData(); } } } startActivityForResult(intent, AppConfig.REQUEST_CODE_DIALOGUE);// 不是呼叫 getActivity().startActivityForResult()。 |
dimen程式碼取值
getDimension方法獲取到資原始檔中定義的dimension值。
1 2 |
Resources res = getResources(); float fontSize = res.getDimension(R.dimen.font_size); |
陣列初始化賦值
1、建立陣列後,通過迴圈對陣列賦值。
例如程式碼:
int [] nums = new int [100];
for(int i=0;inums[i] = i;
}
2、例如程式碼:
int [] nums = {0,1,2,3,4,5,6,7,8,9};
3、int [] nums = new int[]{0,1,2,3,4,5,6,7,8,9};
Fragment.isAdded()
1 2 3 4 5 6 7 8 9 |
Fragment mBeforeFragment = new Fragment(); public void switchFragment(Fragment currentFragment) { if (currentFragment.isAdded()) { getSupportFragmentManager().beginTransaction().hide(mBeforeFragment).show(currentFragment).commit(); } else { getSupportFragmentManager().beginTransaction().hide(mBeforeFragment).add(R.id.container, currentFragment).commit(); } mBeforeFragment = currentFragment; } |
呼叫:
1 |
switchFragment(HomeFragment.newInstance()); |
HomeFragment
1 2 3 4 5 6 7 8 |
public static HomeFragment homeFragment = null; public static HomeFragment newInstance() { if (homeFragment == null) { homeFragment = new HomeFragment(); } return homeFragment; } |
android之inputType屬性
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 |
<EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="phone" /> //文字型別,多為大寫、小寫和數字符號。 android:inputType="none" android:inputType="text" android:inputType="textCapCharacters" 字母大寫 android:inputType="textCapWords" 首字母大寫 android:inputType="textCapSentences" 僅第一個字母大寫 android:inputType="textAutoCorrect" 自動完成 android:inputType="textAutoComplete" 自動完成 android:inputType="textMultiLine" 多行輸入 android:inputType="textImeMultiLine" 輸入法多行(如果支援) android:inputType="textNoSuggestions" 不提示 android:inputType="textUri" 網址 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" 時間鍵盤 |
ImageView.ScaleType
(1)ImageView.ScaleType.center:圖片位於檢視中間,但不執行縮放。
(2)ImageView.ScaleType.CENTER_CROP 按統一比例縮放圖片(保持圖片的尺寸比例)便於圖片的兩維(寬度和高度)等於或者大於相應的檢視的維度
(3)ImageView.ScaleType.CENTER_INSIDE按統一比例縮放圖片(保持圖片的尺寸比例)便於圖片的兩維(寬度和高度)等於或者小於相應的檢視的維度
(4)ImageView.ScaleType.FIT_CENTER縮放圖片使用center
(5)ImageView.ScaleType.FIT_END縮放圖片使用END
(6)ImageView.ScaleType.FIT_START縮放圖片使用START
(7)ImageView.ScaleType.FIT_XY縮放圖片使用XY
(8)ImageView.ScaleType.MATRIX當繪製時使用圖片矩陣縮放
呼叫系統傳送簡訊介面
1 2 3 4 5 6 7 8 9 10 11 12 |
/** * 傳送簡訊 * @param smsBody */ private void sendSMS(String smsBody) { //Uri smsToUri = Uri.parse("smsto:10000"); //如果想指定傳送人 Uri smsToUri = Uri.parse("smsto:"); Intent intent = new Intent(Intent.ACTION_SENDTO, smsToUri); intent.putExtra("sms_body", smsBody); startActivity(intent); } |
跳轉市場搜尋某款軟體
1 2 3 4 5 |
Intent intent = new Intent( "android.intent.action.VIEW"); intent.setData(Uri .parse("market://details?id=com.adobe.flashplayer")); startActivity(intent); |
檢測系統中是否安裝某款軟體
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 |
//檢測系統中是否已經安裝了adobe flash player外掛,外掛的packageName是com.adobe.flashplayer: private boolean check() { PackageManager pm = getPackageManager(); List<PackageInfo> infoList = pm .getInstalledPackages(PackageManager.GET_SERVICES); for (PackageInfo info : infoList) { if ("com.adobe.flashplayer".equals(info.packageName)) { return true; } } return false; } private void isAvilible(String packageName) { PackageInfo packageInfo; try { packageInfo = this.getPackageManager().getPackageInfo(packageName, 0); } catch (NameNotFoundException e) { packageInfo = null; e.printStackTrace(); } if (packageInfo != null) { //1、通過包名 Intent intent = new Intent(); intent = getPackageManager().getLaunchIntentForPackage(packageName); startActivity(intent); //2、通過類名: Intent intent=new Intent(); intent.setComponent(new ComponentName(packageName, "com.joe.internet.Main")); startActivity(intent); } } |
對話方塊選單
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
new AlertDialog.Builder(this) .setTitle("choice") .setItems(new String[] { "選擇1", "選擇2", "選擇3", "選擇4" }, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(MyContentActivity.this, which + "", Toast.LENGTH_SHORT) .show(); } }).show(); |
定義ProgressBar
1 2 3 4 |
<ProgressBar android:id="@+id/mProgress" android:layout_width="wrap_content" android:layout_height="wrap_content" android:indeterminateDrawable="@drawable/progress_rotate" /> |
progress_rotate:
1 2 3 4 5 6 7 8 9 10 11 12 |
<?xml version="1.0" encoding="UTF-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android" > <item> <rotate android:drawable="@drawable/progressbar" android:duration="300" android:fromDegrees="0.0" android:pivotX="50.0%" android:pivotY="50.0%" android:toDegrees="360.0" /> </item> </layer-list> |
幻燈片效果
xml
1 2 3 4 5 6 |
<ProgressBar android:id="@+id/ProgressBar01" style="@style/animStyle" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_centerInParent="true" /> |
style
1 2 3 |
<style name="animStyle" parent="@android:style/Widget.ProgressBar.Large"> <item name="android:indeterminateDrawable">@anim/test</item> </style> |
anim
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?xml version="1.0" encoding="UTF-8"?> <animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="false" > <item android:drawable="@drawable/t1" android:duration="500"/> <item android:drawable="@drawable/t2" android:duration="500"/> <item android:drawable="@drawable/t3" android:duration="500"/> <item android:drawable="@drawable/t4" android:duration="500"/> <item android:drawable="@drawable/t5" android:duration="500"/> </animation-list> |
MD5加密
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 |
public String Md5(String plainText) { String result = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } result = buf.toString().toUpperCase();// 32位的加密(轉成大寫) buf.toString().substring(8, 24);// 16位的加密 } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return result; } |
設定自動跳轉頁面
Timer
1 2 3 4 5 6 7 8 9 10 11 |
Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { // TODO Auto-generated method stub Intent goIntent = new Intent(); goIntent.setClass(LauncherActivity.this, DemoActivity.class); startActivity(goIntent); } }, 3 * 1000); } |
Handler
1 2 3 4 5 6 7 8 |
new Handler().postDelayed(new Runnable() { @Override public void run() { startActivity(new Intent(SplashScreen.this, DomobSampleActivity.class)); finish(); } }, 1000); |
隨機取數
1 2 3 4 5 6 7 8 |
List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < 10; i++) { list.add(i); } Collections.shuffle(list); for (int v : list) { Log.d("wxl", "V===" + v); } |
或:
1 2 3 |
Random random = new Random(); int ran = random.nextInt(keywordsList.size()); String tmp = keywordsList.get(ran).get("keyword").toString(); |
selector下的屬性值
android:state_pressed
如果是true,當被點選時顯示該圖片,如果是false沒被按下時顯示預設。
android:state_focused
true,獲得焦點時顯示;false,沒獲得焦點顯示預設。
android:state_selected
true,當被選擇時顯示該圖片;false,當未被選擇時顯示該圖片。
android:state_checkable
true,當 能使用時顯示該圖片;false,當CheckBox不能使用時顯示該圖片。
android:state_checked
true,當CheckBox選中時顯示該圖片;false,當CheckBox為選中時顯示該圖片。
android:state_enabled
true,當該元件能使用時顯示該圖片;false,當該元件不能使用時顯示該圖片。
android:state_window_focused
true,當此activity獲得焦點在最前面時顯示該圖片;false,當沒在最前面時顯示該圖片。
1 2 3 4 5 6 7 8 |
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:drawable="@drawable/button_pressed"/><!-- pressed --> <item android:state_focused="true" android:drawable="@drawable/button_focused"/><!-- focused --> <item android:drawable="@drawable/button_normal"/><!-- default --> </selector> |
帶下劃線的EditText
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 |
public class LinedEditText extends EditText { private Paint linePaint; private float margin; private int paperColor; public LinedEditText(Context paramContext, AttributeSet paramAttributeSet) { super(paramContext, paramAttributeSet); this.linePaint = new Paint(); } @Override protected void onDraw(Canvas paramCanvas) { paramCanvas.drawColor(this.paperColor); int i = getLineCount();// 得到總的行數 int j = getHeight();// 獲得TextView的高度 int k = getLineHeight();// 獲得TextView的行高 int m = j / k + 1;// 總的線數 if (i < m) i = m; int n = getCompoundPaddingTop(); Log.d("wxl", "n----" + n); paramCanvas.drawLine(0.0F, n, getRight(), n, this.linePaint); for (int i2 = 0;; i2++) { if (i2 >= i) { setPadding(10 + (int) this.margin, 0, 0, 0); super.onDraw(paramCanvas); paramCanvas.restore(); return; } n += k; paramCanvas.drawLine(0.0F, n, getRight(), n, this.linePaint); paramCanvas.save(); } } } |
主要工作就是過載onDraw方法,利用從TextView繼承下來的getLineCount函式獲取文字所佔的行數,以及getLineBounds來獲取特定行的基準高度值,而且這個函式第二個引數會返回此行的“外包裝”值。再利用這些值繪製這一行的線條。為了讓介面的View使用自定義的EditText類,必須在配置檔案中進行設定
關閉鍵盤
1 2 3 4 5 6 7 |
public static void hideSoftInput(Activity activity) { if (activity.getCurrentFocus() != null) ((InputMethodManager) activity .getSystemService(Context.INPUT_METHOD_SERVICE)) .hideSoftInputFromWindow(activity.getCurrentFocus() .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } |
介面不被彈出的鍵盤蓋住
一進入activity就彈出鍵盤
1 2 |
android:windowSoftInputMode="adjustResize" android:windowSoftInputMode="adjustPan|stateAlwaysVisible" |
第一個軟鍵盤和輸入框會完全分離,而第二個輸入框還是會被軟鍵盤蓋住一點點
而且第二個要把兩個屬性疊加起來,為什麼要疊加起來呢,因為如果只用adjustPan 的話需要點選輸入框才會彈出軟鍵盤
在 AndroidMainfest.xml中選擇哪個activity,設定windowSoftInputMode屬性為
1 2 |
adjustUnspecified|stateHidden android:windowSoftInputMode="adjustUnspecified|stateHidden" |
windowSoftInputMode各值的含義:
stateUnspecified:軟鍵盤的狀態並沒有指定,系統將選擇一個合適的狀態或依賴於主題的設定
stateUnchanged:當這個activity出現時,軟鍵盤將一直保持在上一個activity裡的狀態,無論是隱藏還是顯示
stateHidden:使用者選擇activity時,軟鍵盤總是被隱藏
stateAlwaysHidden:當該Activity主視窗獲取焦點時,軟鍵盤也總是被隱藏的
stateVisible:軟鍵盤通常是可見的
stateAlwaysVisible:使用者選擇activity時,軟鍵盤總是顯示的狀態
adjustUnspecified:預設設定,通常由系統自行決定是隱藏還是顯示
adjustResize:該Activity總是調整螢幕的大小以便留出軟鍵盤的空間
adjustPan:當前視窗的內容將自動移動以便當前焦點從不被鍵盤覆蓋和使用者能總是看到輸入內容的部分
控制元件美化Shape
http://wuxiaolong.me/2013/07/09/shape/
獲取版本名稱 VersionName
1 2 3 4 5 6 7 8 9 10 |
public String getVersionName(Context context) { PackageManager manager = context.getPackageManager(); String packageName = context.getPackageName(); try { PackageInfo info = manager.getPackageInfo(packageName, 0); return info.versionName; } catch (NameNotFoundException e) { return "1.0"; } } |
獲取Android手機裝置的IMSI / IMEI 資訊
1 2 3 4 5 6 7 |
TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); String imsi = mTelephonyMgr.getSubscriberId(); String imei = mTelephonyMgr.getDeviceId(); Log.i("wxl", "imsi="+imsi);為null Log.i("wxl", "imei="+imei); 另外不要忘了在AndroidManifest.xml中加上讀取手機狀態的許可權 <uses-permission android:name="android.permission.READ_PHONE_STATE"/> |
自定義Log是否顯示
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 |
public class Log { private static final String TAG = "wxl"; private static final boolean LOG = true; public static void i(String msg) { if (LOG) android.util.Log.i(TAG , msg); } public static void d(String msg) { if (LOG) android.util.Log.d(TAG , msg); } public static void w(String msg) { if (LOG) android.util.Log.w(TAG , msg); } public static void w(String msg, Throwable throwable) { if (LOG) android.util.Log.w(TAG , msg, throwable); } public static void v(String msg) { if (LOG) android.util.Log.v(TAG , msg); } public static void e(String msg) { android.util.Log.e(TAG , msg); } public static void e(String msg, Throwable throwable) { android.util.Log.e(TAG , msg, throwable); } } |
非同步操作AsyncTask
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 |
引數1:向後臺任務的執行方法傳遞引數的型別 ; 引數2:在後臺任務執行過程中,要求主UI執行緒處理中間狀態,通常是一些UI處理中傳遞的引數型別; 引數3:後臺任務執行完返回時的引數型別。 private class MyAsyncTask extends AsyncTask<Integer, String, Void> { // 實現抽象方法doInBackground(),程式碼將在後臺執行緒中執行,由execute()觸發 protected Void doInBackground(Integer... params) { return null; } // 任務啟動,可以在這裡顯示一個對話方塊,這裡簡單處理 protected void onPreExecute() { super.onPreExecute(); } // 取消 protected void onCancelled() { super.onCancelled(); } // 定義後臺程式執行完後的處理 protected void onPostExecute(Void result) { super.onPostExecute(result); Toast.makeText(MainActivity.this, "OK", Toast.LENGTH_SHORT).show(); } // 更新進度,在UI主執行緒執行的內容,將item加入list中。方法中的引數為正規化方式,實質為陣列,由於我們只傳遞了item一個String,要獲取,為values[0] protected void onProgressUpdate(String... values) { super.onProgressUpdate(values); } } |
呼叫:
1 |
new MyAsyncTask().execute(引數1);// 建立後臺任務的物件 |
檢查網路狀態
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 |
public boolean checkNetworkInfo() { ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); // mobile 3G Data Network State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) .getState(); // wifi State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI) .getState(); // 如果3G網路和wifi網路都未連線,且不是處於正在連線狀態 則進入Network Setting介面 由使用者配置網路連線 if (mobile == State.CONNECTED || mobile == State.CONNECTING) return true; if (wifi == State.CONNECTED || wifi == State.CONNECTING) return true; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(getResources().getString(R.string.no_network)) .setCancelable(false) .setPositiveButton( getResources().getString(R.string.configuration), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // 進入無線網路配置介面 startActivity(new Intent( Settings.ACTION_WIRELESS_SETTINGS)); MainActivity.this.finish(); } }) .setNegativeButton(getResources().getString(R.string.quit), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { MainActivity.this.finish(); } }); builder.show(); return false; } |
程式碼判斷呼叫:
1 2 3 4 |
// 檢查網路狀態 if (!checkNetworkInfo()) { return; } |
Html.fromHtml()
讓資料接受網頁的格式
1 2 |
URLEncoder.encode(String s); 網址請求中文解析 …代表省略號 |
URLEncoder.encode
網址請求帶中文
1 |
URLEncoder.encode(content, "utf-8") |
Android中字型加粗
- 在xml檔案中使用
1android:textStyle=”bold”
- Java 程式碼
(網上查XML不能將中文設定成粗體,只能通過Java code。Android 2.2 可以通過XML將中文設定成粗體)
1 2 3 |
TextView tv = (TextView)findViewById(R.id.TextView01); TextPaint tp = tv.getPaint(); tp.setFakeBoldText(true); |
- Html.fromHtml(“”)
1 2 3 |
(1)viewHolder.title.setText(Html.fromHtml("<b>" + listTitle.get(position).get("title") + "</b>")); (2)TextView.setText(Html.fromHtml("<font color=#FF0000>hello</font>")); |
程式碼設定背景圖setImageResource/setBackgroundResource
1 2 3 4 5 |
textView.setBackgroundResource(R.drawable.bg_menu_1);設定背景圖片 textView.setBackgroundColor(0xffffffff); setImageResource與xml中的src的屬性才是相匹配的,而setBackgroundResource是與xml中的background屬性相匹配 的 holder.chat_sound_iv_right.setBackgroundResource(0);//沒有圖片 |
android中的ellipsize
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
用法如下: 在xml中 android:ellipsize = "end" 省略號在結尾 android:ellipsize = "start" 省略號在開頭 android:ellipsize = "middle" 省略號在中間 android:ellipsize = "marquee" 跑馬燈 最好加一個約束android:singleline = "true" 跑馬燈 android:singleLine="true" android:ellipsize="marquee" android:focusableInTouchMode="true" android:focusable="true" android:marqueeRepeatLimit="marquee_forever" android:singleLine=true 表示使用單行文字,多行文字也就無所謂使用Marquee效果了。 android:marqueeRepeatLimit,設定走馬燈滾動的次數。 android:ellipsize,設定了文字過長時如何切斷文字,可以有none, start,middle, end, 如果使用走馬燈效果則設為marquee. android:focusable,Android的預設行為是在控制元件獲得Focus時才會顯示走馬燈效果 |
控制元件點選效果
1 2 3 4 5 |
<selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_focused="true" android:state_pressed="false" android:drawable="@drawable/professional_1"/> <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/professional_1"/> <item android:drawable="@drawable/professional"/> </selector> |
保留小數點
方法一:
1 2 3 4 |
private DecimalFormat df; df = new DecimalFormat("0.0"); float data; df.format(data);//返回值 |
方法二:
1 2 |
double juli = 1569; String result = String.format("%.1f", juli/1000); |
RadioGroup
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 |
<RadioGroup android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" > <RadioButton android:id="@+id/open" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dip" android:layout_marginTop="10dip" android:button="@drawable/radiobutton" android:checked="true" android:text="@string/open_album" android:textColor="#000000" android:textSize="16dip" /> <RadioButton android:id="@+id/secrecy" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dip" android:button="@drawable/radiobutton" android:text="@string/secrecy_album" android:textColor="#000000" android:textSize="16dip" /> </RadioGroup> |
android:button=”@null” 去除RadioButton前面的圓點
android:background=”@drawable/radio” 使用定義的樣式
佔位符%s替換
%d (表示整數)
%f (表示浮點數)
%s (表示字串)
txt.setText(String.format (“被替換%1$s”,”替換內容”));
TextView中巢狀圖片Drawable
1 2 3 4 5 |
Drawable drawable = getResources().getDrawable(R.drawable.ji_dot_nor); drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight()); textView.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null); 說明:setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom) 意思是設定Drawable顯示在text的左、上、右、下位置。(Textview、Button都可以) |
TextView做成分割線
1 2 3 4 5 |
<TextView android:id="@id/textView2" android:layout_width="fill_parent" android:layout_height="2.0px" android:background="@color/orange" /> |
SpannableString單擊文字連結
1 2 3 4 5 6 7 8 9 10 11 |
SpannableString spannableString = new SpannableString(str); spannableString.setSpan(new ClickableSpan() { public void onClick(View view) { // Intent intent = new Intent(ApkTest.this, Apk.class); Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "15261589767")); startActivity(intent); } }, 0, str.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); TextView.setText(spannableString); TextView.setMovementMethod(LinkMovementMethod.getInstance()); |
TextView中文字通過SpannableString
來設定超連結、顏色、字型等屬性
1 2 3 4 5 |
String title =”123456”; SpannableString titleStr = new SpannableString(title); titleStr.setSpan(new ForegroundColorSpan(Color.RED), 0, titleStr.length(), 0); textView.setText(titleStr); |
android:drawableTop屬性
寫在TextView裡,實現圖片+文字
獲取解析度
1 2 3 4 5 |
DisplayMetrics displayMetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); displayMetrics.widthPixels + "x" + displayMetrics.heightPixels; |
程式碼完成控制元件
Button
1 2 3 4 5 6 7 8 |
linearLayout = (LinearLayout) findViewById(R.id.linearLayout2); LayoutParams layoutParams = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1);//1均分屬性 layoutParams.setMargins(10, 10, 10, 10); Button button = new Button(MainActivity.this); button.setLayoutParams(layoutParams); linearLayout.addView(button); |
TextView
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 |
private TextView overlay; private void initOverlay() { LayoutInflater inflater = LayoutInflater.from(this); overlay = (TextView) inflater.inflate(R.layout.overlay, null); overlay.setVisibility(View.INVISIBLE); WindowManager.LayoutParams lp = new WindowManager.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_APPLICATION, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, PixelFormat.TRANSLUCENT); WindowManager windowManager = (WindowManager) this .getSystemService(Context.WINDOW_SERVICE); windowManager.addView(overlay, lp); } <?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:background="#ffffff" android:gravity="center" android:maxWidth="80dip" android:minWidth="80dip" android:padding="5dip" android:textColor="#3399ff" android:textSize="70sp" /> private LinearLayout.LayoutParams layoutParams = null; private LinearLayout.LayoutParams btnParmas; layoutParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); layoutParams.setMargins( (int) getResources().getDimension( R.dimen.lable_left), 0, 0, 0); btnParmas = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, (int) getResources().getDimension( R.dimen.lable_height)); for (int i = 0; i < lables.length; i++) { LinearLayout linearLayout = new LinearLayout(activity); lableColor = random.nextInt(lableColors.length); Button lable = new Button(activity); lable.setText(lables[i]); lable.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL); lable.setTextSize(getResources().getDimension( R.dimen.lable)); lable.setTextColor(getResources().getColor( R.color.white)); lable.setBackgroundResource(lableColors[i]); linearLayout.addView(lable, btnParmas); holder.play_lables.addView(linearLayout, layoutParams); } |
TextWatcher
1 2 3 4 5 6 7 8 9 10 11 |
editText1.addTextChangedListener(watcher); TextWatcher watcher = new TextWatcher() { public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } public void afterTextChanged(Editable arg0) { } }; |
螢幕旋轉時不銷燬
1 2 |
AndroidManifest加入 android:configChanges="orientation|keyboardHidden" |
獲取螢幕方向
1 2 3 4 5 6 7 8 9 10 |
Configuration newConfig = getResources().getConfiguration(); if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){ //橫屏 }else if(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){ //豎屏 }else if(newConfig.hardKeyboardHidden == Configuration.KEYBOARDHIDDEN_NO){ //鍵盤沒關閉。螢幕方向為橫屏 }else if(newConfig.hardKeyboardHidden == Configuration.KEYBOARDHIDDEN_YES){ //鍵盤關閉。螢幕方向為豎屏 } |
List增加資料
簡單
1 2 3 4 5 6 7 8 |
private List<String> getData() { List<String> data = new ArrayList<String>(); data.add("123"); data.add("345"); data.add("456"); data.add("567"); return data; } |
鍵值對
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
private List<Map<String, Object>> getData() { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); Map<String, Object> map = new HashMap<String, Object>(); map.put("title", "G1"); map.put("info", "google 1"); map.put("img", R.drawable.i1); list.add(map); map = new HashMap<String, Object>(); map.put("title", "G2"); map.put("info", "google 2"); map.put("img", R.drawable.i2); list.add(map); map = new HashMap<String, Object>(); map.put("title", "G3"); map.put("info", "google 3"); map.put("img", R.drawable.i3); list.add(map); return list; } |
清除資料:
1 2 |
data.clear(); listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1,getData())); |
LinkedList
1 2 |
LinkedList<String> list = new LinkedList<String>(); list.addFirst("000"); |
驗證是否手機號碼
1 2 3 4 5 6 7 |
public boolean isMobileNO(String mobiles) { String expression = "((^(13|15|18)[0-9]{9}$)|(^0[1,2]{1}\\d{1}-?\\d{8}$)|(^0[3-9] {1}\\d{2}-?\\d{7,8}$)|(^0[1,2]{1}\\d{1}-?\\d{8}-(\\d{1,4})$)|(^0[3-9]{1}\\d{2}-? \\d{7,8}-(\\d{1,4})$))"; Pattern pattern = Pattern.compile(expression); Matcher matcher = pattern.matcher(mobiles); Log.d("wxl", matcher.matches() + ""); return matcher.matches(); } |
正規表示式數字驗證
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public boolean isNumber(String str) { java.util.regex.Pattern pattern=java.util.regex.Pattern.compile("[0-9]*"); java.util.regex.Matcher match=pattern.matcher(str); if(match.matches()==false) { return false; } else { return true; } } |
SharedPreferences
SharedPreferences存資料
1 2 3 4 5 6 7 |
SharedPreferences sharedPreferences = getSharedPreferences("test", Context.MODE_PRIVATE); Editor editor = sharedPreferences.edit();//獲取編輯器 editor.putString("name", "張三"); editor.putInt("age", 24); editor.putBoolean("AutoLogin", false); editor.commit();//提交修改 |
SharedPreferences取資料
1 2 3 4 5 |
SharedPreferences sharedPreferences = getSharedPreferences("test", Context.MODE_PRIVATE); //getString()第二個引數為預設值,如果preference中不存在該key,將返回預設值 String name = sharedPreferences.getString("name", ""); int age = sharedPreferences.getInt("age", 1); boolean autoLogin= sharedPreferences. getBoolean("AutoLogin", false); |
Intent 傳值
簡單傳值
ActivityPage
1 2 3 4 5 |
Intent intent = new Intent(ActivityPage.this, Player.class); //儲存資訊 Bundle mBundle = new Bundle(); mBundle.putString("realname ", realname); intent.putExtras(mBundle); |
Player接受
1 2 3 4 5 6 7 8 |
realname = this.getIntent().getStringExtra("realname"); Intent intent = new Intent(); intent.setClass(HomeActivity.this, CompanyActivity.class); intent.putExtra("mCompanySupply", mCompanySupply); startActivity(intent); CompanyActivity.class: ArrayList<ClassifySub3Bean> mCompanySupply = (ArrayList<ClassifySub3Bean>) getIntent() .getSerializableExtra("mCompanySupply"); |
複雜傳值
A頁面:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
private static final int REQUEST_CODE_A = 0; private static final int RESULT_CODE_B = 0; Intent intent = new Intent(); Bundle bundle = new Bundle(); intent.setClass(MainActivity.this, TestBActivity.class); bundle.putString("msg", textView.getText().toString()); intent.putExtras(bundle); startActivityForResult(intent, REQUEST_CODE_A); protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE_A && resultCode == RESULT_OK) { String str=data.getExtras().getString("result"); } } |
B頁面
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
private static final int RESULT_CODE_B = 0; Intent intent = new Intent(); intent.putExtra("result", textView.getText().toString()); setResult(RESULT_OK, intent); finish(); public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { Intent intent = new Intent(); intent.putExtra("result", "直接返回"); setResult(RESULT_OK, intent); this.finish(); return true; } else { return super.onKeyDown(keyCode, event); } } |
List
1 2 3 4 5 6 7 |
Intent intent = new Intent(); intent.putStringArrayListExtra("mSelectedPhotos", mSelectedPhotos); setResult(RESULT_OK, intent); ArrayList<String> mSelectedPhotos = (ArrayList<String>) intent .getStringArrayListExtra("mSelectedPhotos"); |
xml檔案中匯入另一個xml檔案的方法include
1 2 3 |
<include android:id="@+id/included1" layout="@layout/anotherlayout" /> |
單擊返回鍵兩次退出
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
private static Boolean isExit = false; @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if (isExit == false) { isExit = true; Toast.makeText(this, "再按一次退出程式", Toast.LENGTH_SHORT).show(); new Timer().schedule(new TimerTask() { @Override public void run() { isExit = false; } }, 2000); } else { finish(); System.exit(0); } } return false; } |
或者
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
@Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { long secondTime = System.currentTimeMillis(); if (secondTime - firstTime > 800) {//如果兩次按鍵時間間隔大於800毫秒,則不退出 Toast.makeText(MainActivity.this, "再按一次退出程式...", Toast.LENGTH_SHORT).show(); firstTime = secondTime;//更新firstTime return true; } else { System.exit(0);//否則退出程式 } } return super.onKeyUp(keyCode, event); } |
圖片左右迴圈移動
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 |
TranslateAnimation left, right; right = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, -1f, Animation.RELATIVE_TO_PARENT, -2f, Animation.RELATIVE_TO_PARENT, 0f, Animation.RELATIVE_TO_PARENT, 0f); left = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, -2f, Animation.RELATIVE_TO_PARENT, -1f, Animation.RELATIVE_TO_PARENT, 0f, Animation.RELATIVE_TO_PARENT, 0f); right.setDuration(25000); left.setDuration(25000); right.setFillAfter(true); left.setFillAfter(true); right.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { runImage.startAnimation(left); } }); left.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { runImage.startAnimation(right); } }); runImage.startAnimation(right); |
控制元件左右抖動
res下anim
animlayout.xml
1 2 3 4 5 6 |
<?xml version="1.0" encoding="utf-8"?> <translate xmlns:android="http://schemas.android.com/apk/res/android" android:duration="1000" android:fromXDelta="0" android:interpolator="@anim/cycle_7" android:toXDelta="10" /> |
cycle_7.xml
1 2 3 |
<?xml version="1.0" encoding="utf-8"?> <cycleInterpolator xmlns:android="http://schemas.android.com/apk/res/android" android:cycles="7" /> |
(2)java程式碼
1 2 3 |
Animation shake = AnimationUtils.loadAnimation( MainActivity.this, R.anim.animlayout); btn.setAnimation(shake); |