系統提供了很多可以直接調用的Activity,通過指定的Intent就可以調用,比如打開搜索的:
- Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
- intent.putExtra(SearchManager.QUERY,"searchString")
- startActivity(intent);
- Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
- intent.putExtra(SearchManager.QUERY,"searchString")
- startActivity(intent);
Intent.ACTION_WEB_SEARCH是一個字符串,是“搜索”這個Activity的標識,extra是傳給這個activity的一些數據。發送出這個intent之後,系統根據action字符串Intent.ACTION_WEB_SEARCH知道了是要調用哪個activity,如果有重名,會彈出一個選擇對話框。然後打開此activity,實現想要做的事情。
那麼,我們自己怎麼來實現呢。
首先,寫一個activity,在AndroidManifest.xml裏面的intent-filter中,給這個activity命名,
- <intent-filter>
- <action android:name="chroya.foo"/>
- <category android:name="android.intent.category.DEFAULT"/>
- </intent-filter>
- <intent-filter>
- <action android:name="chroya.foo"/>
- <category android:name="android.intent.category.DEFAULT"/>
- </intent-filter>
然後安裝。安裝完畢之後,你會發現,系統中找不到這個程序。別急,它確實安裝在手機裏面了,但是因爲他不是main的,所以系統不會把他當做Application的入口程序。
而要想打開這個activity,只有知道它名字的人纔可以。跟系統的intent一樣使用。它的名字定義爲"chroya.foo",所以,這裏用這個字符串就可以調用它了:
- Intent intent = new Intent("chroya.foo");
- startActivity(intent);
- Intent intent = new Intent("chroya.foo");
- 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了。
- ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
- ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
- Log.d("", "pkg:"+cn.getPackageName());
- Log.d("", "cls:"+cn.getClassName());
- ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
- ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
- Log.d("", "pkg:"+cn.getPackageName());
- Log.d("", "cls:"+cn.getClassName());
至於這個能做什麼,嘿嘿,我相信你知道的。
如何判斷一個activity是否存在於系統中?
已知包名和類名,如何判斷這個activity是否在系統中存在呢?很簡單,通過intent就行。
- Intent intent = new Intent();
- intent.setClassName("包名", "類名");
- if(getPackageManager().resolveActivity(intent, 0) == null) {
- //說明系統中不存在這個activity
- }
- Intent intent = new Intent();
- intent.setClassName("包名", "類名");
- if(getPackageManager().resolveActivity(intent, 0) == null) {
- //說明系統中不存在這個activity
- }
如何讓應用程序動態全屏和退出全屏?
讓程序全屏的方法,大家都知道,那是靜態的,程序運行之初就申明瞭。但是如果有這樣的需求:要在程序運行的過程中,執行了某個操作而使之全屏,然後還需要退出全屏,怎麼做?
如下:
- WindowManager.LayoutParams attrs = getWindow().getAttributes();
- attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
- getWindow().setAttributes(attrs);
- getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
- WindowManager.LayoutParams attrs = getWindow().getAttributes();
- attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
- getWindow().setAttributes(attrs);
- getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
修改window的LayoutParams參數,然後加上FLAG_LAYOUT_NO_LIMITS標誌,就OK了。window會自動重新佈局,呈現全屏的狀態。
要退出全屏,只需要清除剛纔加上的FLAG_FULLSCREEN參數,然後去掉FLAG_LAYOUT_NO_LIMITS標誌。
如下:
- WindowManager.LayoutParams attrs = getWindow().getAttributes();
- attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
- getWindow().setAttributes(attrs);
- getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
- WindowManager.LayoutParams attrs = getWindow().getAttributes();
- attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
- getWindow().setAttributes(attrs);
- getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
如何獲取狀態欄和標題欄的高度?
1.獲取狀態欄高度:
decorView是window中的最頂層view,可以從window中獲取到decorView,然後decorView有個getWindowVisibleDisplayFrame方法可以獲取到程序顯示的區域,包括標題欄,但不包括狀態欄。於是,我們就可以算出狀態欄的高度了。
- Rect frame = new Rect();
- getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
- int statusBarHeight = frame.top;
- Rect frame = new Rect();
- getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
- int statusBarHeight = frame.top;
2.獲取標題欄高度:
getWindow().findViewById(Window.ID_ANDROID_CONTENT)這個方法獲取到的view就是程序不包括標題欄的部分,然後就可以知道標題欄的高度了。
- int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
- //statusBarHeight是上面所求的狀態欄的高度
- int titleBarHeight = contentTop - statusBarHeight;
- int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
- //statusBarHeight是上面所求的狀態欄的高度
- int titleBarHeight = contentTop - statusBarHeight;
如何將一個視窗(windows)蓋在整個Application的最上面?
- private ImageView waitView;
- private final void showWaiting() {
- try {
- WindowManager.LayoutParams lp = null;
- lp = new WindowManager.LayoutParams(
- ViewGroup.LayoutParams.WRAP_CONTENT,
- ViewGroup.LayoutParams.WRAP_CONTENT,
- WindowManager.LayoutParams.TYPE_TOAST ,
- WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
- | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
- | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
- PixelFormat.TRANSLUCENT
- | WindowManager.LayoutParams.FIRST_SYSTEM_WINDOW) ;
- WindowManager mWindowManager = (WindowManager) G.appInstance
- .getSystemService(Context.WINDOW_SERVICE);
- if (waitView == null) {
- LayoutInflater inflate = (LayoutInflater) G.appInstance
- .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- waitView = (ImageView) inflate.inflate(R.layout.waiting_layout,
- null);
- }
- mWindowManager.addView(waitView, lp);
- } catch (Throwable e) {
- }
- }
- private ImageView waitView;
- private final void showWaiting() {
- try {
- WindowManager.LayoutParams lp = null;
- lp = new WindowManager.LayoutParams(
- ViewGroup.LayoutParams.WRAP_CONTENT,
- ViewGroup.LayoutParams.WRAP_CONTENT,
- WindowManager.LayoutParams.TYPE_TOAST ,
- WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
- | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
- | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
- PixelFormat.TRANSLUCENT
- | WindowManager.LayoutParams.FIRST_SYSTEM_WINDOW) ;
- WindowManager mWindowManager = (WindowManager) G.appInstance
- .getSystemService(Context.WINDOW_SERVICE);
- if (waitView == null) {
- LayoutInflater inflate = (LayoutInflater) G.appInstance
- .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- waitView = (ImageView) inflate.inflate(R.layout.waiting_layout,
- null);
- }
- mWindowManager.addView(waitView, lp);
- } catch (Throwable e) {
- }
- }
注意:
1. 要將window的類型配置成Type_toast。
2.G.appInstance 上下文需要使用Application的context.
如何判斷快捷方式是否已經創建?
快捷方式信息是保存在com.android.launcher的launcher.db的favorites表中
- boolean isInstallShortcut = false ;
- final ContentResolver cr = context.getContentResolver();
- final String AUTHORITY = "com.android.launcher.settings";
- final Uri CONTENT_URI = Uri.parse("content://" +
- AUTHORITY + "/favorites?notify=true");
- Cursor c = cr.query(CONTENT_URI,
- new String[] {"title","iconResource" },
- "title=?",
- new String[] {"XXX" }, null);//XXX表示應用名稱。
- if(c!=null && c.getCount()>0){
- isInstallShortcut = true ;
- }
- /*try {
- while (c.moveToNext()) {
- String tmp = "";
- tmp = c.getString(0);
- }
- } catch (Exception e) {
- } finally {
- c.close();
- }*/
- return isInstallShortcut ;
- }
- boolean isInstallShortcut = false ;
- final ContentResolver cr = context.getContentResolver();
- final String AUTHORITY = "com.android.launcher.settings";
- final Uri CONTENT_URI = Uri.parse("content://" +
- AUTHORITY + "/favorites?notify=true");
- Cursor c = cr.query(CONTENT_URI,
- new String[] {"title","iconResource" },
- "title=?",
- new String[] {"XXX" }, null);//XXX表示應用名稱。
- if(c!=null && c.getCount()>0){
- isInstallShortcut = true ;
- }
- /*try {
- while (c.moveToNext()) {
- String tmp = "";
- tmp = c.getString(0);
- }
- } catch (Exception e) {
- } finally {
- c.close();
- }*/
- return isInstallShortcut ;
- }
要有權限:
<uses-permission android:name="com.android.launcher.permission.READ_SETTINGS"/>
注意:2.2及其之後的版本不能用這個方法判斷!(雖然在launcher.db數據庫裏還有favorites這個表)
如何讓ListView中TextView的字體顏色跟隨焦點的變化?
我們通常需要ListView中某一項選中時,他的字體顏色和原來的不一樣。 如何設置字體的顏色呢? 在佈局文件中TextColor一項來設置顏色,但是不是隻設置一種顏色,而是在不同的條件下設置不同的顏色: 下面是個例子:
- <?xml version="1.0" encoding="utf-8" ?>
- <selector xmlns:android="http://schemas.android.com/apk/res/android">
- <item android:state_enabled="false" android:color="@color/orange"></item>
- <item android:state_window_focused="false" android:color="@color/orange"></item>
- <item android:state_pressed="true" android:color="@color/white"></item>
- <item android:state_selected="true" android:color="@color/white"></item>
- <item android:color="@color/orange"></item>
- </selector>
- 在獲取焦點或者選中的情況下設置爲白色,其他情況設置爲橘黃色。
- <?xml version="1.0" encoding="utf-8" ?>
- <selector xmlns:android="http://schemas.android.com/apk/res/android">
- <item android:state_enabled="false" android:color="@color/orange"></item>
- <item android:state_window_focused="false" android:color="@color/orange"></item>
- <item android:state_pressed="true" android:color="@color/white"></item>
- <item android:state_selected="true" android:color="@color/white"></item>
- <item android:color="@color/orange"></item>
- </selector>
- 在獲取焦點或者選中的情況下設置爲白色,其他情況設置爲橘黃色。
如何在android的一個應用中調用另外一個應用?
- Intent intent = new Intent();
- //第一個參數另一個應用的包名,第二個是需要啓動的類
- intent.setComponent(new ComponentName("com.Ex03_03","com.Ex03_03.Ex03_03"));
- startActivity(intent);
- Intent intent = new Intent();
- //第一個參數另一個應用的包名,第二個是需要啓動的類
- intent.setComponent(new ComponentName("com.Ex03_03","com.Ex03_03.Ex03_03"));
- startActivity(intent);
如何遍歷listView 的的單選框?
- ListView listView = (ListView)findViewById(R.id.配置文件中ListView的ID);
- //全選遍歷ListView的選項,每個選項就相當於佈局配置文件中的RelativeLayout
- for(int i = 0; i < listView.getChildCount(); i++){
- View view = listView.getChildAt(i);
- CheckBox cb = (CheckBox)view.findViewById(R.id.CheckBoxID);
- cb.setChecked(true);
- }
- ListView listView = (ListView)findViewById(R.id.配置文件中ListView的ID);
- //全選遍歷ListView的選項,每個選項就相當於佈局配置文件中的RelativeLayout
- for(int i = 0; i < listView.getChildCount(); i++){
- View view = listView.getChildAt(i);
- CheckBox cb = (CheckBox)view.findViewById(R.id.CheckBoxID);
- cb.setChecked(true);
- }
如何獲取程序版本號?
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.yourcompany.yourapp"
- android:versionCode="109"
- android:versionName="0.1.6.109 dev">
- ...
- </manifest>
- public static int getVersionCode(Context context) {
- PackageManager pm = context.getPackageManager();
- try {
- PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
- return pi.versionCode;
- } catch (NameNotFoundException ex) {}
- return 0;
- }
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.yourcompany.yourapp"
- android:versionCode="109"
- android:versionName="0.1.6.109 dev">
- ...
- </manifest>
- public static int getVersionCode(Context context) {
- PackageManager pm = context.getPackageManager();
- try {
- PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
- return pi.versionCode;
- } catch (NameNotFoundException ex) {}
- return 0;
- }
如何讓Toast充滿全屏?
- Toast t = Toast.makeText(this, "Hello", Toast.LENGTH_SHORT);
- t.setGravity(Gravity.FILL_HORIZONTAL, 0, 0);
- Toast t = Toast.makeText(this, "Hello", Toast.LENGTH_SHORT);
- t.setGravity(Gravity.FILL_HORIZONTAL, 0, 0);
如何更高效簡單的實現界面中的分隔線?
- <View
- android:layout_width="fill_parent"
- android:layout_height="1px"
- android:background="?android:attr/listDivider"
- />
- <View
- android:layout_width="fill_parent"
- android:layout_height="1px"
- android:background="?android:attr/listDivider"
- />
如何發起或刪除另一個程序?
- final Intent intent = new Intent(Intent.ACTION_MAIN, null);
- intent.addCategory(Intent.CATEGORY_LAUNCHER);
- final ComponentName cn = new ComponentName("com.android.settings","com.android.settings.fuelgauge.PowerUsageSummary");
- intent.setComponent(cn);
- intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- startActivity( intent);
- final Intent intent = new Intent(Intent.ACTION_MAIN, null);
- intent.addCategory(Intent.CATEGORY_LAUNCHER);
- final ComponentName cn = new ComponentName("com.android.settings","com.android.settings.fuelgauge.PowerUsageSummary");
- intent.setComponent(cn);
- intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- startActivity( intent);
- //ComponentName 兩個參數一個是包名 一個是包下的主類
- Uri uri = Uri.fromParts("package",“Your Package name here”, null);
- Intent deleteIntent = new Intent(Intent.ACTION_DELETE, uri);
- startActivity(deleteIntent);
- //ComponentName 兩個參數一個是包名 一個是包下的主類
- Uri uri = Uri.fromParts("package",“Your Package name here”, null);
- Intent deleteIntent = new Intent(Intent.ACTION_DELETE, uri);
- startActivity(deleteIntent);
如何爲TextView添加陰影?
values/styles
- <style name="AudioFileInfoOverlayText">
- <item name="android:paddingLeft">4px</item>
- <item name="android:paddingBottom">4px</item>
- <item name="android:textColor">#ffffffff</item>
- <item name="android:textSize">12sp</item>
- <item name="android:shadowColor">#ff00ff00</item>
- <item name="android:shadowDx">5</item>
- <item name="android:shadowDy">3</item>
- <item name="android:shadowRadius">6</item>
- </style>
- <style name="AudioFileInfoOverlayText">
- <item name="android:paddingLeft">4px</item>
- <item name="android:paddingBottom">4px</item>
- <item name="android:textColor">#ffffffff</item>
- <item name="android:textSize">12sp</item>
- <item name="android:shadowColor">#ff00ff00</item>
- <item name="android:shadowDx">5</item>
- <item name="android:shadowDy">3</item>
- <item name="android:shadowRadius">6</item>
- </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" />
如何監測是否靜音?
- AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
- switch (am.getRingerMode()) {
- case AudioManager.RINGER_MODE_SILENT:
- Log.i("MyApp","Silent mode");
- break;
- case AudioManager.RINGER_MODE_VIBRATE:
- Log.i("MyApp","Vibrate mode");
- break;
- case AudioManager.RINGER_MODE_NORMAL:
- Log.i("MyApp","Normal mode");
- break;
- }
- AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
- switch (am.getRingerMode()) {
- case AudioManager.RINGER_MODE_SILENT:
- Log.i("MyApp","Silent mode");
- break;
- case AudioManager.RINGER_MODE_VIBRATE:
- Log.i("MyApp","Vibrate mode");
- break;
- case AudioManager.RINGER_MODE_NORMAL:
- Log.i("MyApp","Normal mode");
- break;
- }
如何設置控件的隨機顯示位置?
- RelativeLayout.LayoutParams parms=(RelativeLayout.LayoutParams)img.getLayoutParams();
- parms.leftMargin = (int) (Math.random() * 320);
- parms.topMargin = (int) (Math.random() * 480);
- img.setLayoutParams(parms);
- img.invalidate();
- RelativeLayout.LayoutParams parms=(RelativeLayout.LayoutParams)img.getLayoutParams();
- parms.leftMargin = (int) (Math.random() * 320);
- parms.topMargin = (int) (Math.random() * 480);
- img.setLayoutParams(parms);
- img.invalidate();
如何讓軟鍵盤顯示/消失?
- InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
- View view = getCurrentFocus();
- if (view != null){
- // imm.showSoftInput(view, 0); //顯示軟鍵盤
- imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
- // imm.hideSoftInputFromWindow(view.getWindowToken(), 0);//隱藏軟鍵盤 // InputMethodManager.HIDE_NOT_ALWAYS);
- }
- InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
- View view = getCurrentFocus();
- if (view != null){
- // imm.showSoftInput(view, 0); //顯示軟鍵盤
- imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
- // imm.hideSoftInputFromWindow(view.getWindowToken(), 0);//隱藏軟鍵盤 // InputMethodManager.HIDE_NOT_ALWAYS);
- }
如何爲Activity屏幕的標題欄添加圖標?
- @Override
- public void onCreate(Bundle icicle) {
- super.onCreate(icicle);
- Window win = getWindow();
- win.requestFeature(Window.FEATURE_LEFT_ICON);
- setContentView(R.layout.mylayout);
- win.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.icon);
- }
- @Override
- public void onCreate(Bundle icicle) {
- super.onCreate(icicle);
- Window win = getWindow();
- win.requestFeature(Window.FEATURE_LEFT_ICON);
- setContentView(R.layout.mylayout);
- win.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.icon);
- }
要注意的是,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)顯示進度條?
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);//先給Activity註冊界面進度條功能
- setContentView(R.layout.main);
- setProgressBarIndeterminateVisibility(true);//在需要顯示進度條的時候調用這個方法
- setProgressBarIndeterminateVisibility(false);//在不需要顯示進度條的時候調用這個方法
- }
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);//先給Activity註冊界面進度條功能
- setContentView(R.layout.main);
- setProgressBarIndeterminateVisibility(true);//在需要顯示進度條的時候調用這個方法
- setProgressBarIndeterminateVisibility(false);//在不需要顯示進度條的時候調用這個方法
- }
如何去掉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橫線?
- 很簡單 簡單的有時候是因爲我們太浮躁
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:gravity="center_horizontal">
- <TabHost
- android:id="@android:id/tabhost"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- ...
- ...
- ...
- </TabHost>
- </LinearLayout>
- 外面加一層LinearLayout
- 很簡單 簡單的有時候是因爲我們太浮躁
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:gravity="center_horizontal">
- <TabHost
- android:id="@android:id/tabhost"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- ...
- ...
- ...
- </TabHost>
- </LinearLayout>
- 外面加一層LinearLayout
如何判斷國家?
- String locale = context.getResources().getConfiguration().locale.getCountry();
- String locale = context.getResources().getConfiguration().locale.getDisplayCountry();
- TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
- String countryCode = tm.getSimCountryIso();
- String locale = context.getResources().getConfiguration().locale.getCountry();
- String locale = context.getResources().getConfiguration().locale.getDisplayCountry();
- TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
- String countryCode = tm.getSimCountryIso();
如何讓屏幕保持一直亮?
- @Override
- protected void onCreate(Bundle icicle) {
- super.onCreate(icicle);
- getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
- }
- @Override
- protected void onCreate(Bundle icicle) {
- super.onCreate(icicle);
- getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
- }
http://wang-peng1.iteye.com/blog/769561
如何檢查sim卡狀態?
- TelephonyManager telMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
- int simState = telMgr.getSimState();
- switch (simState) {
- case TelephonyManager.SIM_STATE_ABSENT:
- // do something
- break;
- case TelephonyManager.SIM_STATE_NETWORK_LOCKED:
- // do something
- break;
- case TelephonyManager.SIM_STATE_PIN_REQUIRED:
- // do something
- break;
- case TelephonyManager.SIM_STATE_PUK_REQUIRED:
- // do something
- break;
- case TelephonyManager.SIM_STATE_READY:
- // do something
- break;
- case TelephonyManager.SIM_STATE_UNKNOWN:
- // do something
- break;
- }
- TelephonyManager telMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
- int simState = telMgr.getSimState();
- switch (simState) {
- case TelephonyManager.SIM_STATE_ABSENT:
- // do something
- break;
- case TelephonyManager.SIM_STATE_NETWORK_LOCKED:
- // do something
- break;
- case TelephonyManager.SIM_STATE_PIN_REQUIRED:
- // do something
- break;
- case TelephonyManager.SIM_STATE_PUK_REQUIRED:
- // do something
- break;
- case TelephonyManager.SIM_STATE_READY:
- // do something
- break;
- case TelephonyManager.SIM_STATE_UNKNOWN:
- // do something
- break;
- }
如何從SMS獲取聯繫人信息?
- ContactItem getContactByAddr(Context context, final SMSItem sms) {
- Uri personUri = Uri.withAppendedPath(
- ContactsContract.PhoneLookup.CONTENT_FILTER_URI, sms.mAddress);
- Cursor cur = context.getContentResolver().query(personUri,
- new String[] { PhoneLookup.DISPLAY_NAME },
- null, null, null );
- if( cur.moveToFirst() ) {
- int nameIdx = cur.getColumnIndex(PhoneLookup.DISPLAY_NAME);
- ContactItem item = new ContactItem();
- item.mName = cur.getString(nameIdx);
- cur.close();
- return item;
- }
- return null;
- }
- ContactItem getContactByAddr(Context context, final SMSItem sms) {
- Uri personUri = Uri.withAppendedPath(
- ContactsContract.PhoneLookup.CONTENT_FILTER_URI, sms.mAddress);
- Cursor cur = context.getContentResolver().query(personUri,
- new String[] { PhoneLookup.DISPLAY_NAME },
- null, null, null );
- if( cur.moveToFirst() ) {
- int nameIdx = cur.getColumnIndex(PhoneLookup.DISPLAY_NAME);
- ContactItem item = new ContactItem();
- item.mName = cur.getString(nameIdx);
- cur.close();
- return item;
- }
- return null;
- }
如何在使用gallery在flinging拖動時候不出現選擇的情況?
這時候需要注意使用
gallery.setCallbackDuringFling(false)
TabHost組件,怎麼調整tab的高度?
- TabWidget tabWidget = mTabHost.getTabWidget();
- int count = tabWidget.getChildCount();
- for(int i = 0;i<count;i++){
- View view = tabWidget.getChildTabViewAt(i);// tabWidget.getChildAt(i);
- view.getLayoutParams().height = 40;
- }
- TabWidget tabWidget = mTabHost.getTabWidget();
- int count = tabWidget.getChildCount();
- for(int i = 0;i<count;i++){
- View view = tabWidget.getChildTabViewAt(i);// tabWidget.getChildAt(i);
- view.getLayoutParams().height = 40;
- }
如何模擬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顧名思義就是層圖形對象。下面直接用一個簡單的代碼表示:
- Bitmap bm = BitmapFactory.decodeResource(getResources(),R.drawable.cwj);
- Drawable[] array = new Drawable[3];
- array[0] = new PaintDrawable(Color.BLACK); //黑色
- array[1] = new PaintDrawable(Color.WHITE); //白色
- array[2] = new BitmapDrawable(bm); //位圖資源
- LayerDrawable ld = new LayerDrawable(array); //參數爲上面的Drawable數組
- ld.setLayerInset(1, 1, 1, 1, 1); //第一個參數1代表數組的第二個元素,爲白色
- ld.setLayerInset(2, 2, 2, 2, 2); //第一個參數2代表數組的第三個元素,爲位圖資源
- mImageView.setImageDrawable(ld);
- Bitmap bm = BitmapFactory.decodeResource(getResources(),R.drawable.cwj);
- Drawable[] array = new Drawable[3];
- array[0] = new PaintDrawable(Color.BLACK); //黑色
- array[1] = new PaintDrawable(Color.WHITE); //白色
- array[2] = new BitmapDrawable(bm); //位圖資源
- LayerDrawable ld = new LayerDrawable(array); //參數爲上面的Drawable數組
- ld.setLayerInset(1, 1, 1, 1, 1); //第一個參數1代表數組的第二個元素,爲白色
- ld.setLayerInset(2, 2, 2, 2, 2); //第一個參數2代表數組的第三個元素,爲位圖資源
- 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即可實現簡單的圖片合成。