之前有談過如何使用adapter更高效的,現在在談談其他的。
一、選擇恰當的圖像尺寸
視圖背景圖總是會填充整個視圖區域,圖像尺寸的不適合會導致圖像的自動縮放,為了避免這種情況,我們可以先將圖片進行縮放到視圖的大小。
originalImage = Bitmap.createScaledBitmap(
originalImage, //被縮放圖
view.getWidth(), //視圖寬度
view.getHright(), //視圖高度
true //雙限行過濾器
);
二、去掉不需要的默認窗口背景
在默認情況下,窗口有一個不透明的背景,有時候我們並不需要他,就可以去掉他。因為更新看不見的窗口是浪費時間的。
去掉的方法:
1.代碼實現:
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//刪除窗口背景
getWindow().setBackgroundDrawable(null);
}
2.xml里實現:
首先去頂你的res/xml/styles.xml里有
<resources>
<style name="NoBackGroundTheme" parent="android:Theme">
<item name="android:windowBackground">@null</item>
</style>
</resources>
然后在你的manifest.xml里聲明
<activity android:name="MyActivity" android:theme="@style/NoBackGroundTheme">
......
</activity>
三、盡可能的使用簡單的布局和視圖
如果一個窗口包含很多的視圖,那么啟動時間長、測量時間長、繪制時間長、布局時間長;
如果視圖樹深度太深,會導致StackOverflowException異常,和用戶界面反映會很慢很慢。
解決的方法:
1.使用TextView的復合drawables,減少層次
如有這樣的布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="@string/hello" />
<Image android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/image" android:background="@drawable/icon" />
</LinearLayout>
我們可以這樣來取代他,從而來將少層次:
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="@string/hello" android:drawableRight="@drawable/icon"/>
2.使用ViewStub延遲展開視圖
默認情況下,使用ViewStub包含的視圖是不可見的。
<ViewStub android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/vs" android:layout="@layout/main"/>
這個里面包含的main視圖是不會展現出來的,如果需要展現出來需要代碼的處理
findViewById(R.id.vs).setVisibility(View.VISIBLE);
或者
findViewById(R.id.vs).inflate();
3.使用<merge>合並視圖
默認情況下,布局文件的根作為一個借點加入到父視圖中,如果使用<merge>可以避免根節點。
如果最外層的布局是FrameLayout,那么可以使用merge替換掉,引用官方說明:
Obviously, using <merge /> works in this case because the parent of an activity's content view is always a FrameLayout. You could not apply this trick if your layout was using a LinearLayout as its root tag for instance.
<merge
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
.....
</merge>
4.使用RelativeLayout減少層次
5.自定義布局