Android有用代碼片段(零)

如何在一個apk中調用另外一個apk中的activity?
   系統提供了很多可以直接調用的Activity,通過指定的Intent就可以調用,比如打開搜索的:
Java代碼  收藏代碼
  1. Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);  
  2. intent.putExtra(SearchManager.QUERY,"searchString")  
  3. startActivity(intent);  
[java] view plaincopy
  1. Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);  
  2. intent.putExtra(SearchManager.QUERY,"searchString")  
  3. startActivity(intent);  

     Intent.ACTION_WEB_SEARCH是一個字符串,是“搜索”這個Activity的標識,extra是傳給這個activity的一些數據。發送出這個intent之後,系統根據action字符串Intent.ACTION_WEB_SEARCH知道了是要調用哪個activity,如果有重名,會彈出一個選擇對話框。然後打開此activity,實現想要做的事情。
    那麼,我們自己怎麼來實現呢。
    首先,寫一個activity,在AndroidManifest.xml裏面的intent-filter中,給這個activity命名,
Xml代碼  收藏代碼
  1. <intent-filter>  
  2.         <action android:name="chroya.foo"/>  
  3.         <category android:name="android.intent.category.DEFAULT"/>  
  4. </intent-filter>  
  1. <intent-filter>  
  2.         <action android:name="chroya.foo"/>  
  3.         <category android:name="android.intent.category.DEFAULT"/>  
  4. </intent-filter>  

    然後安裝。安裝完畢之後,你會發現,系統中找不到這個程序。別急,它確實安裝在手機裏面了,但是因爲他不是main的,所以系統不會把他當做Application的入口程序。
    而要想打開這個activity,只有知道它名字的人纔可以。跟系統的intent一樣使用。它的名字定義爲"chroya.foo",所以,這裏用這個字符串就可以調用它了:
Java代碼  收藏代碼
  1. Intent intent = new Intent("chroya.foo");  
  2. startActivity(intent);  
[java] view plaincopy
  1. Intent intent = new Intent("chroya.foo");  
  2. startActivity(intent);  

       用剛纔舉的那個系統的intent說明,它的activity裏面使用getIntent().getBundleExtra(SearchManager.QUERY)來接收傳遞進來的搜索字符串參數。而這個SearchManager.QUERY是關鍵字。如果要自己實現這種功能,只需要定義好關鍵字,然後從BundleExtra中取就行了。

如何獲取屏幕上正顯示的activity?
       用過ActivityManager的童鞋估計都知道,可以從ActivityManager裏面可以獲取到當前運行的所有任務,所有進程和所有服務,這是任務管理器的核心。
         那麼,從裏面我們可以發掘點什麼出來嗎?
         仔細看getRunningTasks的文檔,裏面說獲取的是系統中"running"的所有task,"running"狀態包括已經被系統凍結的task。而且返回的這個列表是按照順序排列的,也就是說第一個肯定比第二個後運行。
          getRunningTasks有個整型參數,表示返回列表的最大個數。那麼,我們如果把1作爲參數給進去,那麼他返回的task就是當前運行的那個task,然後從task中獲取到最頂層的activity,這個activity就是當前顯示給用戶的那個activity了。
Java代碼  收藏代碼
  1. ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);  
  2. ComponentName cn = am.getRunningTasks(1).get(0).topActivity;  
  3. Log.d("""pkg:"+cn.getPackageName());  
  4. Log.d("""cls:"+cn.getClassName());   
[java] view plaincopy
  1. ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);  
  2. ComponentName cn = am.getRunningTasks(1).get(0).topActivity;  
  3. Log.d("""pkg:"+cn.getPackageName());  
  4. Log.d("""cls:"+cn.getClassName());   

       至於這個能做什麼,嘿嘿,我相信你知道的。

如何判斷一個activity是否存在於系統中?
已知包名和類名,如何判斷這個activity是否在系統中存在呢?很簡單,通過intent就行。
Java代碼  收藏代碼
  1. Intent intent = new Intent();  
  2. intent.setClassName("包名""類名");        
  3. if(getPackageManager().resolveActivity(intent, 0) == null) {  
  4.     //說明系統中不存在這個activity  
  5. }  
[java] view plaincopy
  1. Intent intent = new Intent();  
  2. intent.setClassName("包名""類名");        
  3. if(getPackageManager().resolveActivity(intent, 0) == null) {  
  4.     //說明系統中不存在這個activity  
  5. }  


如何讓應用程序動態全屏和退出全屏?
    讓程序全屏的方法,大家都知道,那是靜態的,程序運行之初就申明瞭。但是如果有這樣的需求:要在程序運行的過程中,執行了某個操作而使之全屏,然後還需要退出全屏,怎麼做?
    如下:
Java代碼  收藏代碼
  1. WindowManager.LayoutParams attrs = getWindow().getAttributes();  
  2. attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;  
  3. getWindow().setAttributes(attrs);  
  4. getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);  
[java] view plaincopy
  1. WindowManager.LayoutParams attrs = getWindow().getAttributes();  
  2. attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;  
  3. getWindow().setAttributes(attrs);  
  4. getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);  

    修改window的LayoutParams參數,然後加上FLAG_LAYOUT_NO_LIMITS標誌,就OK了。window會自動重新佈局,呈現全屏的狀態。
    要退出全屏,只需要清除剛纔加上的FLAG_FULLSCREEN參數,然後去掉FLAG_LAYOUT_NO_LIMITS標誌。
    如下:
Java代碼  收藏代碼
  1. WindowManager.LayoutParams attrs = getWindow().getAttributes();  
  2. attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);  
  3. getWindow().setAttributes(attrs);  
  4. getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);  
[java] view plaincopy
  1. WindowManager.LayoutParams attrs = getWindow().getAttributes();  
  2. attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);  
  3. getWindow().setAttributes(attrs);  
  4. getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);  


如何獲取狀態欄和標題欄的高度?
1.獲取狀態欄高度:
decorView是window中的最頂層view,可以從window中獲取到decorView,然後decorView有個getWindowVisibleDisplayFrame方法可以獲取到程序顯示的區域,包括標題欄,但不包括狀態欄。於是,我們就可以算出狀態欄的高度了。
Java代碼  收藏代碼
  1. Rect frame = new Rect();  
  2. getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);  
  3. int statusBarHeight = frame.top;   
[java] view plaincopy
  1. Rect frame = new Rect();  
  2. getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);  
  3. int statusBarHeight = frame.top;   

2.獲取標題欄高度:
getWindow().findViewById(Window.ID_ANDROID_CONTENT)這個方法獲取到的view就是程序不包括標題欄的部分,然後就可以知道標題欄的高度了。
Java代碼  收藏代碼
  1. int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();  
  2. //statusBarHeight是上面所求的狀態欄的高度  
  3. int titleBarHeight = contentTop - statusBarHeight;  
[java] view plaincopy
  1. int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();  
  2. //statusBarHeight是上面所求的狀態欄的高度  
  3. int titleBarHeight = contentTop - statusBarHeight;  


如何將一個視窗(windows)蓋在整個Application的最上面?
Java代碼  收藏代碼
  1.  private ImageView waitView;  
  2. private final void showWaiting() {  
  3.  try {  
  4. WindowManager.LayoutParams lp = null;  
  5. lp = new WindowManager.LayoutParams(  
  6. ViewGroup.LayoutParams.WRAP_CONTENT,  
  7. ViewGroup.LayoutParams.WRAP_CONTENT,  
  8. WindowManager.LayoutParams.TYPE_TOAST ,  
  9. WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE  
  10. | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE  
  11. | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,  
  12. PixelFormat.TRANSLUCENT  
  13. | WindowManager.LayoutParams.FIRST_SYSTEM_WINDOW) ;  
  14. WindowManager mWindowManager = (WindowManager) G.appInstance  
  15. .getSystemService(Context.WINDOW_SERVICE);  
  16. if (waitView == null) {  
  17. LayoutInflater inflate = (LayoutInflater) G.appInstance  
  18. .getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
  19. waitView = (ImageView) inflate.inflate(R.layout.waiting_layout,  
  20. null);  
  21. }  
  22. mWindowManager.addView(waitView, lp);  
  23. catch (Throwable e) {  
  24. }  
  25. }  
[java] view plaincopy
  1.  private ImageView waitView;  
  2. private final void showWaiting() {  
  3.  try {  
  4. WindowManager.LayoutParams lp = null;  
  5. lp = new WindowManager.LayoutParams(  
  6. ViewGroup.LayoutParams.WRAP_CONTENT,  
  7. ViewGroup.LayoutParams.WRAP_CONTENT,  
  8. WindowManager.LayoutParams.TYPE_TOAST ,  
  9. WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE  
  10. | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE  
  11. | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,  
  12. PixelFormat.TRANSLUCENT  
  13. | WindowManager.LayoutParams.FIRST_SYSTEM_WINDOW) ;  
  14. WindowManager mWindowManager = (WindowManager) G.appInstance  
  15. .getSystemService(Context.WINDOW_SERVICE);  
  16. if (waitView == null) {  
  17. LayoutInflater inflate = (LayoutInflater) G.appInstance  
  18. .getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
  19. waitView = (ImageView) inflate.inflate(R.layout.waiting_layout,  
  20. null);  
  21. }  
  22. mWindowManager.addView(waitView, lp);  
  23. catch (Throwable e) {  
  24. }  
  25. }  

注意: 
1. 要將window的類型配置成Type_toast。 
2.G.appInstance 上下文需要使用Application的context. 

如何判斷快捷方式是否已經創建?
快捷方式信息是保存在com.android.launcher的launcher.db的favorites表中
Java代碼  收藏代碼
  1.     boolean isInstallShortcut = false ;  
  2.     final ContentResolver cr = context.getContentResolver();  
  3.     final String AUTHORITY = "com.android.launcher.settings";  
  4.     final Uri CONTENT_URI = Uri.parse("content://" +  
  5.                      AUTHORITY + "/favorites?notify=true");  
  6.       
  7.     Cursor c = cr.query(CONTENT_URI,  
  8.     new String[] {"title","iconResource" },  
  9.     "title=?",  
  10.     new String[] {"XXX" }, null);//XXX表示應用名稱。  
  11.             if(c!=null && c.getCount()>0){  
  12.         isInstallShortcut = true ;  
  13.     }  
  14.     /*try { 
  15.         while (c.moveToNext()) { 
  16.                                     String tmp = ""; 
  17.             tmp = c.getString(0); 
  18.         } 
  19.         } catch (Exception e) { 
  20.  
  21.         } finally { 
  22.             c.close(); 
  23.         }*/  
  24.     return isInstallShortcut ;  
  25. }  
[java] view plaincopy
  1.     boolean isInstallShortcut = false ;  
  2.     final ContentResolver cr = context.getContentResolver();  
  3.     final String AUTHORITY = "com.android.launcher.settings";  
  4.     final Uri CONTENT_URI = Uri.parse("content://" +  
  5.                      AUTHORITY + "/favorites?notify=true");  
  6.       
  7.     Cursor c = cr.query(CONTENT_URI,  
  8.     new String[] {"title","iconResource" },  
  9.     "title=?",  
  10.     new String[] {"XXX" }, null);//XXX表示應用名稱。  
  11.             if(c!=null && c.getCount()>0){  
  12.         isInstallShortcut = true ;  
  13.     }  
  14.     /*try { 
  15.         while (c.moveToNext()) { 
  16.                                     String tmp = ""; 
  17.             tmp = c.getString(0); 
  18.         } 
  19.         } catch (Exception e) { 
  20.  
  21.         } finally { 
  22.             c.close(); 
  23.         }*/  
  24.     return isInstallShortcut ;  
  25. }  

要有權限: 
<uses-permission android:name="com.android.launcher.permission.READ_SETTINGS"/>
注意:2.2及其之後的版本不能用這個方法判斷!(雖然在launcher.db數據庫裏還有favorites這個表)

如何讓ListView中TextView的字體顏色跟隨焦點的變化?
我們通常需要ListView中某一項選中時,他的字體顏色和原來的不一樣。 如何設置字體的顏色呢? 在佈局文件中TextColor一項來設置顏色,但是不是隻設置一種顏色,而是在不同的條件下設置不同的顏色: 下面是個例子: 
Xml代碼  收藏代碼
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android">  
  3. <item android:state_enabled="false" android:color="@color/orange"></item>  
  4. <item android:state_window_focused="false" android:color="@color/orange"></item>  
  5. <item android:state_pressed="true" android:color="@color/white"></item>  
  6. <item android:state_selected="true" android:color="@color/white"></item>  
  7. <item android:color="@color/orange"></item>  
  8. </selector>   
  9. 在獲取焦點或者選中的情況下設置爲白色,其他情況設置爲橘黃色。  
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android">  
  3. <item android:state_enabled="false" android:color="@color/orange"></item>  
  4. <item android:state_window_focused="false" android:color="@color/orange"></item>  
  5. <item android:state_pressed="true" android:color="@color/white"></item>  
  6. <item android:state_selected="true" android:color="@color/white"></item>  
  7. <item android:color="@color/orange"></item>  
  8. </selector>   
  9. 在獲取焦點或者選中的情況下設置爲白色,其他情況設置爲橘黃色。  



如何在android的一個應用中調用另外一個應用?
Java代碼  收藏代碼
  1. Intent intent = new Intent();  
  2. //第一個參數另一個應用的包名,第二個是需要啓動的類  
  3. intent.setComponent(new ComponentName("com.Ex03_03","com.Ex03_03.Ex03_03"));  
  4. startActivity(intent);  
[java] view plaincopy
  1. Intent intent = new Intent();  
  2. //第一個參數另一個應用的包名,第二個是需要啓動的類  
  3. intent.setComponent(new ComponentName("com.Ex03_03","com.Ex03_03.Ex03_03"));  
  4. startActivity(intent);  


如何遍歷listView 的的單選框?
Java代碼  收藏代碼
  1. ListView listView = (ListView)findViewById(R.id.配置文件中ListView的ID);  
  2. //全選遍歷ListView的選項,每個選項就相當於佈局配置文件中的RelativeLayout  
  3. for(int i = 0; i < listView.getChildCount(); i++){  
  4.       View view = listView.getChildAt(i);  
  5.       CheckBox cb = (CheckBox)view.findViewById(R.id.CheckBoxID);  
  6.       cb.setChecked(true);  
  7. }  
[java] view plaincopy
  1. ListView listView = (ListView)findViewById(R.id.配置文件中ListView的ID);  
  2. //全選遍歷ListView的選項,每個選項就相當於佈局配置文件中的RelativeLayout  
  3. for(int i = 0; i < listView.getChildCount(); i++){  
  4.       View view = listView.getChildAt(i);  
  5.       CheckBox cb = (CheckBox)view.findViewById(R.id.CheckBoxID);  
  6.       cb.setChecked(true);  
  7. }  


如何獲取程序版本號?
Java代碼  收藏代碼
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.    package="com.yourcompany.yourapp"   
  4.    android:versionCode="109"  
  5.    android:versionName="0.1.6.109 dev">  
  6.    ...  
  7. </manifest>  
  8.  public static int getVersionCode(Context context) {  
  9.    PackageManager pm = context.getPackageManager();  
  10.    try {  
  11.       PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);  
  12.       return pi.versionCode;  
  13.    } catch (NameNotFoundException ex) {}  
  14.    return 0;  
  15. }  
[java] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.    package="com.yourcompany.yourapp"   
  4.    android:versionCode="109"  
  5.    android:versionName="0.1.6.109 dev">  
  6.    ...  
  7. </manifest>  
  8.  public static int getVersionCode(Context context) {  
  9.    PackageManager pm = context.getPackageManager();  
  10.    try {  
  11.       PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);  
  12.       return pi.versionCode;  
  13.    } catch (NameNotFoundException ex) {}  
  14.    return 0;  
  15. }  


如何讓Toast充滿全屏?
Java代碼  收藏代碼
  1. Toast t = Toast.makeText(this"Hello", Toast.LENGTH_SHORT);  
  2. t.setGravity(Gravity.FILL_HORIZONTAL, 00);  
[java] view plaincopy
  1. Toast t = Toast.makeText(this"Hello", Toast.LENGTH_SHORT);  
  2. t.setGravity(Gravity.FILL_HORIZONTAL, 00);  


如何更高效簡單的實現界面中的分隔線?
Java代碼  收藏代碼
  1. <View    
  2.     android:layout_width="fill_parent"     
  3.     android:layout_height="1px"     
  4.     android:background="?android:attr/listDivider"     
  5. />  
[java] view plaincopy
  1. <View    
  2.     android:layout_width="fill_parent"     
  3.     android:layout_height="1px"     
  4.     android:background="?android:attr/listDivider"     
  5. />  


如何發起或刪除另一個程序?
Java代碼  收藏代碼
  1. final Intent intent = new Intent(Intent.ACTION_MAIN, null);  
  2. intent.addCategory(Intent.CATEGORY_LAUNCHER);  
  3. final ComponentName cn = new ComponentName("com.android.settings","com.android.settings.fuelgauge.PowerUsageSummary");  
  4. intent.setComponent(cn);  
  5. intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  6. startActivity( intent);  
[java] view plaincopy
  1. final Intent intent = new Intent(Intent.ACTION_MAIN, null);  
  2. intent.addCategory(Intent.CATEGORY_LAUNCHER);  
  3. final ComponentName cn = new ComponentName("com.android.settings","com.android.settings.fuelgauge.PowerUsageSummary");  
  4. intent.setComponent(cn);  
  5. intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  6. startActivity( intent);  

Java代碼  收藏代碼
  1. //ComponentName 兩個參數一個是包名 一個是包下的主類  
  2. Uri uri = Uri.fromParts("package",“Your Package name here”, null);  
  3. Intent deleteIntent = new Intent(Intent.ACTION_DELETE, uri);  
  4. startActivity(deleteIntent);  
[java] view plaincopy
  1. //ComponentName 兩個參數一個是包名 一個是包下的主類  
  2. Uri uri = Uri.fromParts("package",“Your Package name here”, null);  
  3. Intent deleteIntent = new Intent(Intent.ACTION_DELETE, uri);  
  4. startActivity(deleteIntent);  


如何爲TextView添加陰影?
values/styles
Xml代碼  收藏代碼
  1. <style name="AudioFileInfoOverlayText">   
  2.     <item name="android:paddingLeft">4px</item>   
  3.     <item name="android:paddingBottom">4px</item>   
  4.     <item name="android:textColor">#ffffffff</item>   
  5.     <item name="android:textSize">12sp</item>   
  6.     <item name="android:shadowColor">#ff00ff00</item>   
  7.     <item name="android:shadowDx">5</item>   
  8.     <item name="android:shadowDy">3</item>   
  9.     <item name="android:shadowRadius">6</item>  
  10. </style>  
  1. <style name="AudioFileInfoOverlayText">   
  2.     <item name="android:paddingLeft">4px</item>   
  3.     <item name="android:paddingBottom">4px</item>   
  4.     <item name="android:textColor">#ffffffff</item>   
  5.     <item name="android:textSize">12sp</item>   
  6.     <item name="android:shadowColor">#ff00ff00</item>   
  7.     <item name="android:shadowDx">5</item>   
  8.     <item name="android:shadowDy">3</item>   
  9.     <item name="android:shadowRadius">6</item>  
  10. </style>  

<TextView android:id="@+id/info" 
       android:layout_width="fill_parent" 
       android:layout_height="wrap_content" 
       style="@style/AudioFileInfoOverlayText" 
       android:text="aaaa"
       android:gravity="center" />

如何監測是否靜音?
Java代碼  收藏代碼
  1. AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);   
  2. switch (am.getRingerMode()) {   
  3.     case AudioManager.RINGER_MODE_SILENT:   
  4.         Log.i("MyApp","Silent mode");   
  5.         break;   
  6.     case AudioManager.RINGER_MODE_VIBRATE:   
  7.         Log.i("MyApp","Vibrate mode");   
  8.         break;   
  9.     case AudioManager.RINGER_MODE_NORMAL:   
  10.         Log.i("MyApp","Normal mode");   
  11.         break;   
  12. }   
[java] view plaincopy
  1. AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);   
  2. switch (am.getRingerMode()) {   
  3.     case AudioManager.RINGER_MODE_SILENT:   
  4.         Log.i("MyApp","Silent mode");   
  5.         break;   
  6.     case AudioManager.RINGER_MODE_VIBRATE:   
  7.         Log.i("MyApp","Vibrate mode");   
  8.         break;   
  9.     case AudioManager.RINGER_MODE_NORMAL:   
  10.         Log.i("MyApp","Normal mode");   
  11.         break;   
  12. }   


如何設置控件的隨機顯示位置?
Java代碼  收藏代碼
  1. RelativeLayout.LayoutParams parms=(RelativeLayout.LayoutParams)img.getLayoutParams();  
  2. parms.leftMargin = (int) (Math.random() * 320);  
  3. parms.topMargin = (int) (Math.random() * 480);  
  4. img.setLayoutParams(parms);          
  5. img.invalidate();  
[java] view plaincopy
  1. RelativeLayout.LayoutParams parms=(RelativeLayout.LayoutParams)img.getLayoutParams();  
  2. parms.leftMargin = (int) (Math.random() * 320);  
  3. parms.topMargin = (int) (Math.random() * 480);  
  4. img.setLayoutParams(parms);          
  5. img.invalidate();  


如何讓軟鍵盤顯示/消失?
Java代碼  收藏代碼
  1. InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);      
  2. View view = getCurrentFocus();      
  3. if (view != null){      
  4.      // imm.showSoftInput(view, 0); //顯示軟鍵盤      
  5.       imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);    
  6.      // imm.hideSoftInputFromWindow(view.getWindowToken(), 0);//隱藏軟鍵盤  // InputMethodManager.HIDE_NOT_ALWAYS);    
  7. }    
[java] view plaincopy
  1. InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);      
  2. View view = getCurrentFocus();      
  3. if (view != null){      
  4.      // imm.showSoftInput(view, 0); //顯示軟鍵盤      
  5.       imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);    
  6.      // imm.hideSoftInputFromWindow(view.getWindowToken(), 0);//隱藏軟鍵盤  // InputMethodManager.HIDE_NOT_ALWAYS);    
  7. }    


如何爲Activity屏幕的標題欄添加圖標?
Java代碼  收藏代碼
  1. @Override    
  2. public void onCreate(Bundle icicle) {    
  3.     super.onCreate(icicle);    
  4.     Window win = getWindow();    
  5.     win.requestFeature(Window.FEATURE_LEFT_ICON);        
  6.     setContentView(R.layout.mylayout);     
  7.     win.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.icon);    
  8. }  
[java] view plaincopy
  1. @Override    
  2. public void onCreate(Bundle icicle) {    
  3.     super.onCreate(icicle);    
  4.     Window win = getWindow();    
  5.     win.requestFeature(Window.FEATURE_LEFT_ICON);        
  6.     setContentView(R.layout.mylayout);     
  7.     win.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.icon);    
  8. }  

要注意的是,win.setFeatureDrawableResource必須在setContentView之後,不然就沒有效果。

如何讓ListView自動滾動?
注意stackFromBottom以及transcriptMode這兩個屬性。類似Market客戶端的低端不斷滾動。
<ListView android:id="listCWJ"  
     android:layout_width="fill_parent"  
     android:layout_height="fill_parent"  
     android:stackFromBottom="true"    
     android:transcriptMode="alwaysScroll"  
/>

如何設置桌面壁紙?
希望在你的程序中能設置桌面壁紙嗎?很簡單,首先我們需要取得設置壁紙的權限。和其它權限一樣,只要在配置文件中加上以下配置信息即可。
<uses-permission android:name="android.permission.SET_WALLPAPER" />
然後在程序中調用如下代碼即可設置桌面壁紙:
getApplicationContext().setWallpaper(bitmap)

如何在標題欄(titlebar)顯示進度條?
Java代碼  收藏代碼
  1. protected void onCreate(Bundle savedInstanceState) {  
  2.         super.onCreate(savedInstanceState);  
  3.         requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);//先給Activity註冊界面進度條功能  
  4.         setContentView(R.layout.main);  
  5.         setProgressBarIndeterminateVisibility(true);//在需要顯示進度條的時候調用這個方法  
  6.         setProgressBarIndeterminateVisibility(false);//在不需要顯示進度條的時候調用這個方法  
  7. }  
[java] view plaincopy
  1. protected void onCreate(Bundle savedInstanceState) {  
  2.         super.onCreate(savedInstanceState);  
  3.         requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);//先給Activity註冊界面進度條功能  
  4.         setContentView(R.layout.main);  
  5.         setProgressBarIndeterminateVisibility(true);//在需要顯示進度條的時候調用這個方法  
  6.         setProgressBarIndeterminateVisibility(false);//在不需要顯示進度條的時候調用這個方法  
  7. }  


如何去掉activity頂部的gradient?
<style name="Theme.Foo" parent="android:style/Theme.Light"> 
    <item name="android:windowContentOverlay">@null</item> 
</style>
<activity android:name=".FooActivity" 
          android:theme="@style/Theme.Foo"> ... 
http://wang-peng1.iteye.com/blog/680015

如何讓ScrollView強制滑到底部?
scroll.fullScroll(View.FOCUS_DOWN) 就可以了

如何ViewFlipper去掉多餘空間?
ViewFlipper flipper = (ViewFlipper)findViewById(R.id.flipper); 
flipper.setMeasureAllChildren(false); 

如何去掉tabhost橫線?
Java代碼  收藏代碼
  1. 很簡單 簡單的有時候是因爲我們太浮躁  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"       
  3.     android:orientation="vertical"   
  4.     android:layout_width="fill_parent"   
  5.     android:layout_height="fill_parent"   
  6.    
  7.     android:gravity="center_horizontal">         
  8.    <TabHost    
  9.     android:id="@android:id/tabhost"       
  10.     android:layout_width="fill_parent"   
  11.     android:layout_height="fill_parent"   
  12.     >   
  13. ...   
  14. ...   
  15. ...   
  16.     </TabHost>   
  17.     </LinearLayout>   
  18. 外面加一層LinearLayout  
[java] view plaincopy
  1. 很簡單 簡單的有時候是因爲我們太浮躁  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"       
  3.     android:orientation="vertical"   
  4.     android:layout_width="fill_parent"   
  5.     android:layout_height="fill_parent"   
  6.    
  7.     android:gravity="center_horizontal">         
  8.    <TabHost    
  9.     android:id="@android:id/tabhost"       
  10.     android:layout_width="fill_parent"   
  11.     android:layout_height="fill_parent"   
  12.     >   
  13. ...   
  14. ...   
  15. ...   
  16.     </TabHost>   
  17.     </LinearLayout>   
  18. 外面加一層LinearLayout  


如何判斷國家?
Java代碼  收藏代碼
  1. String locale = context.getResources().getConfiguration().locale.getCountry();    
  2. String locale = context.getResources().getConfiguration().locale.getDisplayCountry();   
  3. TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);   
  4. String countryCode = tm.getSimCountryIso();   
[java] view plaincopy
  1. String locale = context.getResources().getConfiguration().locale.getCountry();    
  2. String locale = context.getResources().getConfiguration().locale.getDisplayCountry();   
  3. TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);   
  4. String countryCode = tm.getSimCountryIso();   


如何讓屏幕保持一直亮?
Java代碼  收藏代碼
  1. @Override  
  2.     protected void onCreate(Bundle icicle) {  
  3.         super.onCreate(icicle);  
  4.   
  5.         getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);  
  6.     }  
[java] view plaincopy
  1. @Override  
  2.     protected void onCreate(Bundle icicle) {  
  3.         super.onCreate(icicle);  
  4.   
  5.         getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);  
  6.     }  

http://wang-peng1.iteye.com/blog/769561

如何檢查sim卡狀態?
Java代碼  收藏代碼
  1. TelephonyManager telMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);  
  2.     int simState = telMgr.getSimState();  
  3.             switch (simState) {  
  4.                 case TelephonyManager.SIM_STATE_ABSENT:  
  5.                     // do something  
  6.                     break;  
  7.                 case TelephonyManager.SIM_STATE_NETWORK_LOCKED:  
  8.                     // do something  
  9.                     break;  
  10.                 case TelephonyManager.SIM_STATE_PIN_REQUIRED:  
  11.                     // do something  
  12.                     break;  
  13.                 case TelephonyManager.SIM_STATE_PUK_REQUIRED:  
  14.                     // do something  
  15.                     break;  
  16.                 case TelephonyManager.SIM_STATE_READY:  
  17.                     // do something  
  18.                     break;  
  19.                 case TelephonyManager.SIM_STATE_UNKNOWN:  
  20.                     // do something  
  21.                     break;  
  22.             }  
[java] view plaincopy
  1. TelephonyManager telMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);  
  2.     int simState = telMgr.getSimState();  
  3.             switch (simState) {  
  4.                 case TelephonyManager.SIM_STATE_ABSENT:  
  5.                     // do something  
  6.                     break;  
  7.                 case TelephonyManager.SIM_STATE_NETWORK_LOCKED:  
  8.                     // do something  
  9.                     break;  
  10.                 case TelephonyManager.SIM_STATE_PIN_REQUIRED:  
  11.                     // do something  
  12.                     break;  
  13.                 case TelephonyManager.SIM_STATE_PUK_REQUIRED:  
  14.                     // do something  
  15.                     break;  
  16.                 case TelephonyManager.SIM_STATE_READY:  
  17.                     // do something  
  18.                     break;  
  19.                 case TelephonyManager.SIM_STATE_UNKNOWN:  
  20.                     // do something  
  21.                     break;  
  22.             }  


如何從SMS獲取聯繫人信息?
Java代碼  收藏代碼
  1. ContactItem getContactByAddr(Context context, final SMSItem sms) {    
  2.     Uri personUri = Uri.withAppendedPath(    
  3.             ContactsContract.PhoneLookup.CONTENT_FILTER_URI, sms.mAddress);    
  4.     Cursor cur = context.getContentResolver().query(personUri,    
  5.             new String[] { PhoneLookup.DISPLAY_NAME },    
  6.             nullnullnull );    
  7.     if( cur.moveToFirst() ) {    
  8.         int nameIdx = cur.getColumnIndex(PhoneLookup.DISPLAY_NAME);    
  9.         ContactItem item = new ContactItem();    
  10.         item.mName = cur.getString(nameIdx);    
  11.        cur.close();    
  12.        return item;    
  13.    }    
  14.    return null;    
  15. }  
[java] view plaincopy
  1. ContactItem getContactByAddr(Context context, final SMSItem sms) {    
  2.     Uri personUri = Uri.withAppendedPath(    
  3.             ContactsContract.PhoneLookup.CONTENT_FILTER_URI, sms.mAddress);    
  4.     Cursor cur = context.getContentResolver().query(personUri,    
  5.             new String[] { PhoneLookup.DISPLAY_NAME },    
  6.             nullnullnull );    
  7.     if( cur.moveToFirst() ) {    
  8.         int nameIdx = cur.getColumnIndex(PhoneLookup.DISPLAY_NAME);    
  9.         ContactItem item = new ContactItem();    
  10.         item.mName = cur.getString(nameIdx);    
  11.        cur.close();    
  12.        return item;    
  13.    }    
  14.    return null;    
  15. }  


如何在使用gallery在flinging拖動時候不出現選擇的情況?
這時候需要注意使用
gallery.setCallbackDuringFling(false)

TabHost組件,怎麼調整tab的高度?
Java代碼  收藏代碼
  1. TabWidget tabWidget = mTabHost.getTabWidget();  
  2. int count = tabWidget.getChildCount();  
  3. for(int i = 0;i<count;i++){  
  4.         View view = tabWidget.getChildTabViewAt(i);// tabWidget.getChildAt(i);  
  5.         view.getLayoutParams().height = 40;  
  6. }  
[java] view plaincopy
  1. TabWidget tabWidget = mTabHost.getTabWidget();  
  2. int count = tabWidget.getChildCount();  
  3. for(int i = 0;i<count;i++){  
  4.         View view = tabWidget.getChildTabViewAt(i);// tabWidget.getChildAt(i);  
  5.         view.getLayoutParams().height = 40;  
  6. }  


如何模擬SDcard?
看圖:


應該能看明白。

如何自定義ListView行間的分割線?
在Android平臺中系統控件提供了靈活的自定義選項,所有基於ListView或者說AbsListView實現的widget控件均可以通過下面的方法設置行間距的分割線,分割線可以自定義顏色、或圖片。
在ListView中我們使用屬性   android:divider="#FF0000" 定義分隔符爲紅色,當然這裏值可以指向一個drawable圖片對象,如果使用了圖片可能高度大於系統默認的像素,可以自己設置高度比如6個像素   android:dividerHeight="6px" ,Android開發網提示當然在Java中ListView也有相關方法可以設置。

如何在EditText中顯示隱藏Android輸入法窗口?
細心的網友可能發現我們在使用EditText時,會自動的彈出輸入法面板,這裏我們提供多種方法可以不讓程序默認升起IME窗口。
1.讓EditText失去焦點,使用EditText的clearFocus方法
2. 強制隱藏Android輸入法窗口,在IME類中我們通過
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 實例化輸入法控制對象,通過hideSoftInputFromWindow來控制,其中第一個參數綁定的爲需要隱藏輸入法的EditText對象,比如imm.hideSoftInputFromWindow(etAndroid123.getWindowToken(), 0);

如何實現TextView多行本文滾動?
Android中我們爲了實現文本的滾動可以在ScrollView中嵌入一個TextView,其實TextView自己也可以實現多行滾動的,畢竟ScrollView必須只能有一個直接的子類佈局。只要在layout中簡單設置幾個屬性就可以輕鬆實現
  <TextView  
    android:id="@+id/tvCWJ"  
    android:layout_width="fill_parent"  
    android:layout_height="wrap_content"  
    android:scrollbars="vertical"   <!--垂直滾動條 -->
    android:singleLine="false"       <!--實現多行 -->
    android:maxLines="15"            <!--最多不超過15行 -->
    android:textColor="#FF0000"
    /> 
當然我們爲了讓TextView動起來,還需要用到TextView的setMovementMethod方法設置一個滾動實例,代碼如下
TextView tvAndroid123 = (TextView)findViewById(R.id.tvCWJ);   
tvAndroid123.setMovementMethod(ScrollingMovementMethod.getInstance());

如何對View截屏?
對於自己的View實現一些繪圖或子類化的技術時可以不用系統級這樣的方法,我們可以通過
view.setDrawingCacheEnabled(true); //其中View是你需要截圖的的View
Bitmap bm = view.getDrawingCache(); 

如何區別onRetainNonConfigurationInstance和getLastNonConfigurationInstance?
很多網友可能知道Android橫豎屏切換時會觸發onSaveInstanceState,而還原時會產生onRestoreInstanceState,但是Android的Activity類還有一個方法名爲onRetainNonConfigurationInstance和getLastNonConfigurationInstance這兩個方法。
我們可以通過  onRetainNonConfigurationInstance 代替 onSaveInstanceState,比如距離2
@Override
  public Object onRetainNonConfigurationInstance() 
{    
       //這裏需要保存的內容,在切換時不是bundle了,我們可以直接通過Object來代替
      return obj;
}

在恢復窗口時,我們可以不使用 onRestoreInstanceState,而代替的是 getLastNonConfigurationInstance 方法。我們可以直接在onCreate中使用,比如
Object obj = getLastNonConfigurationInstance();     最終obj的內容就是上次切換時的內容。
這裏Android123提醒大家,每次Activity橫豎屏切換時onCreate方法都會被觸發。

如何區別AsyncTask和Thread+Handler?
很多網友可能發現Android平臺很多應用使用的都是AsyncTask,而並非Thread和Handler去更新UI,這裏Android123給大家說下他們到底有什麼區別,我們平時應該使用哪種解決方案。從Android 1.5開始系統將AsyncTask引入到android.os包中,過去在很早1.1和1.0 SDK時其實官方將其命名爲UserTask,其內部是JDK 1.5開始新增的concurrent庫,做過J2EE的網友可能明白併發庫效率和強大性,比Java原始的Thread更靈活和強大,但對於輕量級的使用更爲佔用系統資源。Thread是Java早期爲實現多線程而設計的,比較簡單不支持concurrent中很多特性在同步和線程池類中需要自己去實現很多的東西,對於分佈式應用來說更需要自己寫調度代碼,而爲了Android UI的刷新Google引入了Handler和Looper機制,它們均基於消息實現,有事可能消息隊列阻塞或其他原因無法準確的使用。

  Android開發網推薦大家使用AsyncTask代替Thread+Handler的方式,不僅調用上更爲簡單,經過實測更可靠一些,Google在Browser中大量使用了異步任務作爲處理耗時的I/O操作,比如下載文件、讀寫數據庫等等,它們在本質上都離不開消息,但是AsyncTask相比Thread加Handler更爲可靠,更易於維護,但AsyncTask缺點也是有的比如一旦線程開啓即dobackground方法執行後無法給線程發送消息,僅能通過預先設置好的標記來控制邏輯,當然可以通過線程的掛起等待標誌位的改變來通訊,對於某些應用Thread和Handler以及Looper可能更靈活。

如何使多個Drawable疊加(合成圖片)?
大家可能知道Bitmap的疊加處理在Android平臺中可以通過Canvas一層一層的畫就行了,而Drawable中如何處理呢? 除了使用BitmapDrawable的getBitmap方法將Drawable轉換爲Bitmap外,今天Android123給大家說下好用簡單的LayerDrawable類,LayerDrawable顧名思義就是層圖形對象。下面直接用一個簡單的代碼表示:
Java代碼  收藏代碼
  1. Bitmap bm = BitmapFactory.decodeResource(getResources(),R.drawable.cwj);  
  2.     Drawable[] array = new Drawable[3];  
  3.      array[0] = new PaintDrawable(Color.BLACK); //黑色  
  4.      array[1] = new PaintDrawable(Color.WHITE); //白色     
  5.      array[2] = new BitmapDrawable(bm); //位圖資源          
  6.     LayerDrawable ld = new LayerDrawable(array); //參數爲上面的Drawable數組  
  7.     ld.setLayerInset(11111);  //第一個參數1代表數組的第二個元素,爲白色  
  8.     ld.setLayerInset(22222); //第一個參數2代表數組的第三個元素,爲位圖資源  
  9.     mImageView.setImageDrawable(ld);  
[java] view plaincopy
  1. Bitmap bm = BitmapFactory.decodeResource(getResources(),R.drawable.cwj);  
  2.     Drawable[] array = new Drawable[3];  
  3.      array[0] = new PaintDrawable(Color.BLACK); //黑色  
  4.      array[1] = new PaintDrawable(Color.WHITE); //白色     
  5.      array[2] = new BitmapDrawable(bm); //位圖資源          
  6.     LayerDrawable ld = new LayerDrawable(array); //參數爲上面的Drawable數組  
  7.     ld.setLayerInset(11111);  //第一個參數1代表數組的第二個元素,爲白色  
  8.     ld.setLayerInset(22222); //第一個參數2代表數組的第三個元素,爲位圖資源  
  9.     mImageView.setImageDrawable(ld);  

上面的方法中LayerDrawable是關鍵,Android開發網提示setLayerInset方法原型爲public void setLayerInset (int index, int l, int t, int r, int b) 其中第一個參數爲層的索引號,後面的四個參數分別爲left、top、right和bottom。對於簡單的圖片合成我們可以將第一和第二層的PaintDrawable換成BitmapDrawable即可實現簡單的圖片合成。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章