Android有用代碼片斷(二)

記得2011年的時候,整理了android有用代碼片斷這篇文章,後來,越添加越多,非常不方便,決定,每20條爲一篇,分開記載,不少內容是從別的博客上面轉載而來,因爲疏忽沒有說明來處,敬請做者諒解!

二11、獲取手機屏幕分辨率
[java] view plain copy
  1. DisplayMetrics dm = new DisplayMereics();
  2. getWindowManager().getDefaultDisplay().getMetrics(dm);
  3. float width = dm.widthPixels * dm.density;
  4. float height = dm.heightPixels * dm.density
在這裏問什麼要乘以 dm.density 了,是由於經過dm.widthPixels的到的結果始終是320,不是真實的屏幕分辨率,因此要乘以dm.density獲得真實的分辨率。
二12、在Activity裏面播放背景音樂
[java] view plain copy
  1. public void onCreate(Bundle savedInstanceState) {
  2. super.onCreate(savedInstanceState);
  3. setContentView(R.layout.mainlay);
  4. mediaPlayer = MediaPlayer.create(this, R.raw.mu);
  5. mediaPlayer.setLooping(true);
  6. mediaPlayer.start();
  7. }


二十3、讓程序的界面不隨機器的重力感應而翻轉html

第一種方法,在manifast文件裏面java

[html] view plain copy
  1. <activity
  2. android:screenOrientation="portrait">
  3. </activity>

第二種,在代碼裏面

[java] view plain copy
  1. setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

二十4、使activity全屏顯示

[java] view plain copy
  1. requestWindowFeature(Window.FEATURE_NO_TITLE);
  2. getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN ,
  3. WindowManager.LayoutParams. FLAG_FULLSCREEN);

二十5、在RelativeLayout中使selector要注意點android

關於selector的使用方法,能夠參考http://blog.csdn.net/aomandeshangxiao/article/details/6759576這篇文章,今天,遇到在RelativeLayout中添加background爲selector後沒有反應的問題,尋摸了很長時間,一直沒有找到緣由,其實只要加上一句代碼就徹底能夠解決:正則表達式

[java] view plain copy
  1. <span style="font-size:16px;">RelativeLayout 裏面加上android:clickable="true"</span>

這樣,RelativLayout就會出如今selector裏面定義的效果。


二十6、顯示或隱藏虛擬鍵盤數組

[java] view plain copy
  1. 顯示:
  2. InputMethodManager imm = (InputMethodManager)(getSystemService(Context.INPUT_METHOD_SERVICE));
  3. imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
  4. 隱藏:
  5. InputMethodManager imm = (InputMethodManager)(getSystemService(Context.INPUT_METHOD_SERVICE));
  6. imm.hideSoftInputFromWindow(m_edit.getWindowToken(), 0);

二十7、退出程序時清除通知中信息 app

[java] view plain copy
  1. NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
  2. nm.cancelAll();

二十8、建立快捷方式ide

[java] view plain copy
  1. Intent intent=new Intent();
  2. //設置快捷方式的圖標
  3. intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(this, R.drawable.img));
  4. //設置快捷方法的名稱
  5. intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "點擊啓動哥的程序"); //設置點擊快鍵圖標的響應操做
[java] view plain copy
  1. intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(this,MainActivity.class));
  2. //傳遞Intent對象給系統
  3. setResult(RESULT_OK, intent);
  4. finish();


二十9、獲取文件中的類名:函數

[java] view plain copy
  1. String path = context.getPackageManager().getApplicationInfo(
  2. context.getPackageName(), 0).sourceDir;
  3. DexFile dexfile = new DexFile(path);
  4. Enumeration<String> entries = dexfile.entries();
  5. while (entries.hasMoreElements()) {
  6. String name = (String) entries.nextElement();
  7. ......
  8. }



三十. TextView中的getTextSize返回值是以像素(px)爲單位的,oop

而setTextSize()是以sp爲單位的.佈局

因此若是直接用返回的值來設置會出錯,解決辦法是:

用setTextSize()的另一種形式,能夠指定單位:

[java] view plain copy
  1. TypedValue.COMPLEX_UNIT_PX : Pixels
  2. TypedValue.COMPLEX_UNIT_SP : Scaled Pixels
  3. 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陰影字體設置

[html] view plain copy
  1. <TextView android:id="@+id/tvText1"
  2. android:layout_width="wrap_content"
  3. android:layout_height="wrap_content"
  4. android:text="text1"
  5. android:textSize="30sp"
  6. android:textStyle="bold"
  7. android:textColor="#FFFFFF"
  8. android:shadowColor="#ff0000ff"
  9. android:shadowDx="5"
  10. android:shadowDy="5"
  11. android:shadowRadius="10"/>


android:shadowColor 陰影顏色

android:shadowDx 陰影的水平偏移量

android:shadowDy 陰影的垂直偏移量

android:shadowRadius 陰影的範圍

爲了統一風格和代碼的複用,一般能夠把這個樣式抽取放入到style.xml文件中

[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <resources>
  3. <style name="textstyle">
  4. <item name="android:shadowColor">#ff0000ff</item>
  5. <item name="android:shadowRadius">10</item>
  6. <item name="android:shadowDx">5</item>
  7. <item name="android:shadowDy">5</item>
  8. </style>
  9. </resources>
[html] view plain copy
  1. <TextView
  2. style="@style/textstyle"
  3. android:layout_width="fill_parent"
  4. android:layout_height="wrap_content"
  5. android:text="字體樣式"
  6. android:textSize="30sp"
  7. android:textStyle="bold" />

三十5、android實現手機震動功能

[java] view plain copy
  1. import android.app.Activity;
  2. import android.app.Service;
  3. import android.os.Vibrator;
  4. public class TipHelper {
  5. public static void Vibrate(final Activity activity, long milliseconds) {
  6. Vibrator vib = (Vibrator) activity.getSystemService(Service.VIBRATOR_SERVICE);
  7. vib.vibrate(milliseconds);
  8. }
  9. public static void Vibrate(final Activity activity, long[] pattern,boolean isRepeat) {
  10. Vibrator vib = (Vibrator) activity.getSystemService(Service.VIBRATOR_SERVICE);
  11. vib.vibrate(pattern, isRepeat ? 1 : -1);
  12. }
  13. }


還須要在AndroidManifest.xml 中添加震動權限:

[html] view plain copy
  1. <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下 加:

[html] view plain copy
  1. android:windowSoftInputMode="adjustPan"

三十8、listview中item中button可點擊:

[html] view plain copy
  1. android:descendantFocusability="blocksDescendants"

三十9、獲取移動設備的IP地址:

[java] view plain copy
  1. public class Tools {
  2. public static String getLocalIpAddress() {
  3. try {
  4. for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
  5. NetworkInterface intf = en.nextElement();
  6. for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
  7. InetAddress inetAddress = enumIpAddr.nextElement();
  8. if (!inetAddress.isLoopbackAddress()) {
  9. return inetAddress.getHostAddress().toString();
  10. }
  11. }
  12. }
  13. } catch (SocketException ex) {
  14. Log.e("出錯啦", ex.toString());
  15. }
  16. return null;
  17. }
  18. }
  19. 而後
  20. WifiManager wm = (WifiManager)getSystemService(WIFI_SERVICE);
  21. WifiInfo wi = wm.getConnectionInfo();
  22. System.out.println("IP地址是:"+Tools.getLocalIpAddress());
  23. System.out.println("SSID:"+wi.getSSID());
  24. 最後記得加兩個權限
  25. <uses-permission android:name="android.permission.INTERNET"/>
  26. <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>


四10、高仿小米launcher跨屏拖動item(GridView長按item進行拖動

觸發長按事件後浮動原理:

  1. windowParams = new WindowManager.LayoutParams();
  2.   windowParams.gravity = Gravity.TOP | Gravity.LEFT;
  3.   windowParams.x = x - itemWidth / 2;
  4.   windowParams.y = y - itemHeight / 2;
  5.   windowParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
  6.   windowParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
  7.   ImageView iv = new ImageView(getContext());
  8.   iv.setImageBitmap(bm);
  9.   windowManager = (WindowManager) getContext().getSystemService(
  10.   Context.WINDOW_SERVICE);// "window"
  11.   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); 拖動效果:

  1. if (dragImageView != null) {
  2.   windowParams.alpha = 0.6f;
  3.   windowParams.x = x - itemWidth / 2;
  4.   windowParams.y = y - itemHeight / 2;
  5.   windowManager.updateViewLayout(dragImageView, windowParams);
  6.   }
相關文章
相關標籤/搜索