記得2011年的時候,整理了android有用代碼片斷這篇文章,後來,越添加越多,非常不方便,決定,每20條爲一篇,分開記載,不少內容是從別的博客上面轉載而來,因爲疏忽沒有說明來處,敬請做者諒解!
二11、獲取手機屏幕分辨率
- DisplayMetrics dm = new DisplayMereics();
-
- getWindowManager().getDefaultDisplay().getMetrics(dm);
-
- float width = dm.widthPixels * dm.density;
-
- float height = dm.heightPixels * dm.density
在這裏問什麼要乘以 dm.density 了,是由於經過dm.widthPixels的到的結果始終是320,不是真實的屏幕分辨率,因此要乘以dm.density獲得真實的分辨率。
二12、在Activity裏面播放背景音樂
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.mainlay);
- mediaPlayer = MediaPlayer.create(this, R.raw.mu);
- mediaPlayer.setLooping(true);
- mediaPlayer.start();
-
- }
二十3、讓程序的界面不隨機器的重力感應而翻轉html
第一種方法,在manifast文件裏面java
- <activity
- android:screenOrientation="portrait">
- </activity>
第二種,在代碼裏面
- setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
二十4、使activity全屏顯示
- requestWindowFeature(Window.FEATURE_NO_TITLE);
- getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN ,
- WindowManager.LayoutParams. FLAG_FULLSCREEN);
二十5、在RelativeLayout中使selector要注意點android
關於selector的使用方法,能夠參考http://blog.csdn.net/aomandeshangxiao/article/details/6759576這篇文章,今天,遇到在RelativeLayout中添加background爲selector後沒有反應的問題,尋摸了很長時間,一直沒有找到緣由,其實只要加上一句代碼就徹底能夠解決:正則表達式
- <span style="font-size:16px;">RelativeLayout 裏面加上android:clickable="true"</span>
這樣,RelativLayout就會出如今selector裏面定義的效果。
二十6、顯示或隱藏虛擬鍵盤數組
- 顯示:
- InputMethodManager imm = (InputMethodManager)(getSystemService(Context.INPUT_METHOD_SERVICE));
- imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
-
- 隱藏:
- InputMethodManager imm = (InputMethodManager)(getSystemService(Context.INPUT_METHOD_SERVICE));
- imm.hideSoftInputFromWindow(m_edit.getWindowToken(), 0);
二十7、退出程序時清除通知中信息 app
- NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
- nm.cancelAll();
二十8、建立快捷方式ide
- Intent intent=new Intent();
- //設置快捷方式的圖標
- intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(this, R.drawable.img));
- //設置快捷方法的名稱
- intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "點擊啓動哥的程序"); //設置點擊快鍵圖標的響應操做
- intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(this,MainActivity.class));
- //傳遞Intent對象給系統
- setResult(RESULT_OK, intent);
- finish();
二十9、獲取文件中的類名:函數
- String path = context.getPackageManager().getApplicationInfo(
- context.getPackageName(), 0).sourceDir;
- DexFile dexfile = new DexFile(path);
- Enumeration<String> entries = dexfile.entries();
- while (entries.hasMoreElements()) {
- String name = (String) entries.nextElement();
- ......
- }
三十. TextView中的getTextSize返回值是以像素(px)爲單位的,oop
而setTextSize()是以sp爲單位的.佈局
因此若是直接用返回的值來設置會出錯,解決辦法是:
用setTextSize()的另一種形式,能夠指定單位:
- TypedValue.COMPLEX_UNIT_PX : Pixels
- TypedValue.COMPLEX_UNIT_SP : Scaled Pixels
- TypedValue.COMPLEX_UNIT_DIP : Device Independent Pixels
三十一. 在繼承自View時,繪製bitmap時,須要將圖片放到新建的drawable-xdpi
中,不然容易出現繪製大小發生改變
三十二. 在文字中加下劃線: textView.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
三十三. scrollView是繼承自frameLayout,因此在使用LayoutParams時須要用frameLayout的
三十4、android陰影字體設置
- <TextView android:id="@+id/tvText1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="text1"
- android:textSize="30sp"
- android:textStyle="bold"
- android:textColor="#FFFFFF"
- android:shadowColor="#ff0000ff"
- android:shadowDx="5"
- android:shadowDy="5"
- android:shadowRadius="10"/>
android:shadowColor 陰影顏色
android:shadowDx 陰影的水平偏移量
android:shadowDy 陰影的垂直偏移量
android:shadowRadius 陰影的範圍
爲了統一風格和代碼的複用,一般能夠把這個樣式抽取放入到style.xml文件中
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
- <style name="textstyle">
- <item name="android:shadowColor">#ff0000ff</item>
- <item name="android:shadowRadius">10</item>
- <item name="android:shadowDx">5</item>
- <item name="android:shadowDy">5</item>
- </style>
- </resources>
- <TextView
- style="@style/textstyle"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="字體樣式"
- android:textSize="30sp"
- android:textStyle="bold" />
三十5、android實現手機震動功能
- import android.app.Activity;
- import android.app.Service;
- import android.os.Vibrator;
-
- public class TipHelper {
- public static void Vibrate(final Activity activity, long milliseconds) {
- Vibrator vib = (Vibrator) activity.getSystemService(Service.VIBRATOR_SERVICE);
- vib.vibrate(milliseconds);
- }
- public static void Vibrate(final Activity activity, long[] pattern,boolean isRepeat) {
- Vibrator vib = (Vibrator) activity.getSystemService(Service.VIBRATOR_SERVICE);
- vib.vibrate(pattern, isRepeat ? 1 : -1);
- }
- }
還須要在AndroidManifest.xml 中添加震動權限:
- <uses-permission android:name="android.permission.VIBRATE" />
經過上面操做,咱們可使用TipHelper所定義的函數了。兩個Vibrate函數的參數簡單介紹以下:
final Activity activity :調用該方法的Activity實例
long milliseconds :震動的時長,單位是毫秒
long[] pattern :自定義震動模式 。數組中數字的含義依次是[靜止時長,震動時長,靜止時長,震動時長。。。]時長的單位是毫秒
boolean isRepeat : 是否反覆震動,若是是true,反覆震動,若是是false,只震動一次
三十6、經常使用的正則表達式
^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$ //email地址
^[a-zA-z]+://(\w+(-\w+)*)(\.(\w+(-\w+)*))*(\?\S*)?$ //url
^(d{2}|d{4})-((0([1-9]{1}))|(1[1|2]))-(([0-2]([1-9]{1}))|(3[0|1]))$ //年-月-日
^((0([1-9]{1}))|(1[1|2]))/(([0-2]([1-9]{1}))|(3[0|1]))/(d{2}|d{4})$ //月/日/年
^([w-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([w-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$ //Emil
^((\+?[0-9]{2,4}\-[0-9]{3,4}\-)|([0-9]{3,4}\-))?([0-9]{7,8})(\-[0-9]+)?$ //電話號碼
^(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5])$ //IP地址
(^\s*)|(\s*$) // 首尾空格
^[a-zA-Z][a-zA-Z0-9_]{4,15}$ // 賬號是否合法(字母開頭,容許5-16字節,容許字母數字下劃線)
^[1-9]*[1-9][0-9]*$ // 騰訊QQ號
三十7、輸入框不擠壓activity佈局:
在manifest文件activity下 加:
- android:windowSoftInputMode="adjustPan"
三十8、listview中item中button可點擊:
- android:descendantFocusability="blocksDescendants"
三十9、獲取移動設備的IP地址:
- public class Tools {
- public static String getLocalIpAddress() {
- try {
- for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
- NetworkInterface intf = en.nextElement();
- for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
- InetAddress inetAddress = enumIpAddr.nextElement();
- if (!inetAddress.isLoopbackAddress()) {
- return inetAddress.getHostAddress().toString();
- }
- }
- }
- } catch (SocketException ex) {
- Log.e("出錯啦", ex.toString());
- }
- return null;
- }
- }
- 而後
- WifiManager wm = (WifiManager)getSystemService(WIFI_SERVICE);
- WifiInfo wi = wm.getConnectionInfo();
- System.out.println("IP地址是:"+Tools.getLocalIpAddress());
- System.out.println("SSID:"+wi.getSSID());
- 最後記得加兩個權限
- <uses-permission android:name="android.permission.INTERNET"/>
- <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
四10、高仿小米launcher跨屏拖動item(GridView長按item進行拖動
觸發長按事件後浮動原理:
- windowParams = new WindowManager.LayoutParams();
- windowParams.gravity = Gravity.TOP | Gravity.LEFT;
- windowParams.x = x - itemWidth / 2;
- windowParams.y = y - itemHeight / 2;
- windowParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
- windowParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
- ImageView iv = new ImageView(getContext());
- iv.setImageBitmap(bm);
- windowManager = (WindowManager) getContext().getSystemService(
- Context.WINDOW_SERVICE);// "window"
- windowManager.addView(iv, windowParams);
windowParams = new WindowManager.LayoutParams(); windowParams.gravity = Gravity.TOP | Gravity.LEFT; windowParams.x = x - itemWidth / 2; windowParams.y = y - itemHeight / 2; windowParams.height = WindowManager.LayoutParams.WRAP_CONTENT; windowParams.width = WindowManager.LayoutParams.WRAP_CONTENT; ImageView iv = new ImageView(getContext()); iv.setImageBitmap(bm); windowManager = (WindowManager) getContext().getSystemService( Context.WINDOW_SERVICE);// "window" windowManager.addView(iv, windowParams);
拖動效果:
- if (dragImageView != null) {
- windowParams.alpha = 0.6f;
- windowParams.x = x - itemWidth / 2;
- windowParams.y = y - itemHeight / 2;
- windowManager.updateViewLayout(dragImageView, windowParams);
- }