常用Android小代碼(不斷更新中....)

本章內容爲“雜文”,記下Android中常用的小代碼片段:


一:獲取資源文件、其中屬性

例如:獲取String.xml的app_name 其中getString爲資源文件類型

this.getResources().getString(R.string.app_name)


二:Intent攜帶Bundl傳遞數據(這裏測試實體)
實體在傳送的時候需要先:序列化  一種:android自帶Parcelable  二種:java的Serializable倆者都可以!
分別先實現 implements它們的接口,前者需要重寫幾個方法、後者直接實現接口比較簡單,但是Parcelable功能更加完善!根據需求而定!
序列化 可以參考:http://www.apkbus.com/android-13576-1-1.html
Parcelable 可以參考:http://ipjmc.iteye.com/blog/1314145

案例:
一般把HomeActivity頁面獲得實體(CurrentOrder) ==> OrderDetailsActivity頁面 一般選Serializable 

步驟1: 序列化:

步驟2:HomeActivity跳轉綁定實體:

/**
	 * Intent “做橋樑”Bundle “運貨車 CurrentOrder(實體) “做貨物”
	 * */
	Intent intent = new Intent(HomeActivity.this,OrderDetailsActivity.class);
	Bundle bundle = new Bundle();
	// bundle都是已 K--V 形式
	bundle.putSerializable("currentOrder", currentOrder);
	intent.putExtras(bundle);
	startActivity(intent);


步驟3:OrderDetailsActivity 接受數據取出實體

	/**
	 * 從Intent中取出 Bundle
	 * 在Bundle通過K 取出 V
	 * */
	Bundle bundle = this.getIntent().getExtras();
	CurrentOrder order = (CurrentOrder) bundle.get("currentOrder");


三:數據存儲之SharedPrefences簡介

一般用於記住密碼、常量本地保存、方便、快捷優點.....  

1.存

步驟:  獲得實例---->打開---->存值---->提交

	SharedPreferences sp =this.getSharedPreferences("Login", MODE_PRIVATE);
	Editor editor = sp.edit();
	editor.putString("Name", "admin");
	editor.putString("Password", "admin");
	editor.commit();

2.取

步驟:  獲得實例---->取值K

		SharedPreferences sp = getSharedPreferences("Login", MODE_PRIVATE);
		 // * 未找K時候,此時返回第二個參數
		String name = sp.getString("Name", "");
		String password = sp.getString("Password", "");

Context.MODE_PRIVATE    =  0 爲默認操作模式,私有本身訪問,寫入的內容會覆蓋原文件的內容
Context.MODE_APPEND    =  32768 模式會檢查文件是否存在,存在就往文件追加內容,否則就創建新文件
Context.MODE_WORLD_READABLE =  1 表示當前文件可以被其他應用讀取
Context.MODE_WORLD_WRITEABLE =  2 
表示當前文件可以被其他應用寫入

可以參考①:http://blog.csdn.net/zuolongsnail/article/details/6556703

可以參考②:http://liuzhichao.com/p/522.html


四:獲取assets目錄文件.轉換String

/**
	 * 從assets目錄下獲取String
	 * @param context	當前上下文
	 * @param fileName 文件名字 (json.txt)
	 * @return  
	 */
	public static String convertStreamToString(Context context,String fileName ){
		String result = "";
		try {
			//讀取文件
			InputStream is = context.getAssets().open(fileName);
			//文件大小
			int size = is.available();
			byte[] buffer = new byte[size];
			//寫入
			is.read(buffer);
			//關閉
			is.close();
			//轉換
			 result = new String(buffer, "GB2312");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	
	}


四:迭代Map集合

		 Iterator it = MapTable.entrySet().iterator();  
	        while (it.hasNext()) {  
	            Map.Entry e = (Map.Entry) it.next();  
	            System.out.println("Key: " + e.getKey() + "; Value: " + e.getValue());  
	        } 


五:無標題欄

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- 無標題 -->
    <style name="notitle" parent="AppBaseTheme">
        <item name="android:windowNoTitle">true</item>
    </style>

</resources>

// android:theme="@style/notitle" 



六:ViewHolder模式 工具

適配器中簡單的ViewHolder

	/**
	 * 一個ViewHolder模式 工具
	 *
	 */
	public static class ViewHolder {
		@SuppressWarnings("unchecked")
		public static <T extends View> T get(View view, int id) {
			SparseArray<View> viewHolder = (SparseArray<View>) view.getTag();
			if (viewHolder == null) {
				viewHolder = new SparseArray<View>();
				view.setTag(viewHolder);
			}
			View childView = viewHolder.get(id);
			if (childView == null) {
				childView = view.findViewById(id);
				viewHolder.put(id, childView);
			}
			return (T) childView;
		}
	}

對應寫法:

		//簡單寫法
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = LayoutInflater.from(context).inflate(R.layout.gridsbj, null);
			}
			ImageButton sbjBtn=ViewHolder.get(convertView, R.id.sbjBtn);
			sbjBtn.setBackgroundResource(R.drawable.button_second_red_del_logout_220x220);
			return convertView;
		}




七:線程UI更新,緩停執行

如果你對於Android的Thread+Handler方式感覺繁瑣,不如用  Activity.runOnUiThread, 注意該方法是在Activity下面的。

		this.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Toast.makeText(MainActivity.this, "這樣也可以更新UI線程", Toast.LENGTH_SHORT).show();
			}
		});


5秒後執行一個方法,不用計時器。
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Log.d(" ", "5秒後我訪客執行");
			}
		}, 5000);




七:自定義ActionBar

        this.getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        this.getActionBar().setCustomView(R.layout.actionbar);

xml:

<?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="wrap_content"
    android:layout_gravity="center"
    android:orientation="horizontal">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:lines="1"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:text="YOUR ACTIVITY TITLE"
        android:textColor="#aabbcc"
        android:textSize="24sp" />


</LinearLayout>

關於ActionBar的介紹:

1:ActionBar(上)

2:ActionBae(下)


八:單位換DIP、px、sp

可以在android.util 包下有這樣的換算

TypedValue.applyDimension(int unit, float value,DisplayMetrics metrics)

例如:TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, width, getResources().getDisplayMetrics());

可以看到 TypedValue. unit 裏面的數據類型..

/** {@link #TYPE_DIMENSION} complex unit: Value is raw pixels. */
public static final int COMPLEX_UNIT_PX = 0;
/** {@link #TYPE_DIMENSION} complex unit: Value is Device Independent
 *  Pixels. */
public static final int COMPLEX_UNIT_DIP = 1;
/** {@link #TYPE_DIMENSION} complex unit: Value is a scaled pixel. */
public static final int COMPLEX_UNIT_SP = 2;
/** {@link #TYPE_DIMENSION} complex unit: Value is in points. */
public static final int COMPLEX_UNIT_PT = 3;
/** {@link #TYPE_DIMENSION} complex unit: Value is in inches. */
public static final int COMPLEX_UNIT_IN = 4;
/** {@link #TYPE_DIMENSION} complex unit: Value is in millimeters. */
public static final int COMPLEX_UNIT_MM = 5;


發佈了49 篇原創文章 · 獲贊 8 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章