本章内容为“杂文”,记下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.htmlParcelable 可以参考:http://ipjmc.iteye.com/blog/1314145

案例:
一般把HomeActivity页面获得实体(CurrentOrder) ==> OrderDetailsActivity页面 一般选Serializable 

步骤1: 序列化:

android软件管理代码 android程序代码_代码集合

步骤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://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;