一、優化布局
1、使用ConstraintLayout布局,避免使用RelativeLayout和LinearLayout。
2、減少布局層級,可以使用<merge>
標籤來消除嵌套的布局。
3、使用ViewStub
延遲載入布局,只有在需要時才載入。
4、使用RecyclerView
或ListView
來實現列表,復用View,減少view的創建。
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:text="Hello World!" />
</android.support.constraint.ConstraintLayout>
二、圖片優化
1、儘可能使用矢量圖而不是點陣圖。
2、壓縮圖片,可以通過pngcrush
、pngout
、jpegtran
等工具優化圖片。
3、使用Picasso
或Glide
等圖片載入庫來載入圖片,它們可以對圖片進行縮放、壓縮、內存緩存等優化。
Picasso.get()
.load("http://example.com/image.png")
.resize(600, 400)
.centerCrop()
.into(imageView);
三、內存優化
1、避免內存泄漏,使用LeakCanary
等工具來檢測內存泄漏問題。
2、使用WeakReference
來引用Activity或Fragment等可以被回收的對象。
3、盡量避免使用靜態變數,靜態變數會一直存在內存中,直到應用退出。
4、使用Profiler
工具來分析內存泄漏和內存佔用情況。
public class MainActivity extends AppCompatActivity {
private static TextView textView; // 需要避免使用靜態變數
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text_view);
}
}
四、代碼優化
1、減少不必要的計算,可以使用Handler.postDelayed()
代替Timer.schedule()
來避免重複計算。
2、使用TextUtils.isEmpty()
來判斷字元串是否為空。
3、使用@Override
註解來標註方法是覆蓋了父類或實現了介面的方法。
4、使用StringBuilder
代替+
操作符來拼接字元串,避免頻繁創建String對象。
private Handler mHandler = new Handler();
private Runnable mRunnable = new Runnable() {
@Override
public void run() {
// do something
mHandler.postDelayed(this, 1000);
}
};
五、啟動優化
1、避免在Application.onCreate()
方法中初始化耗時操作,可以使用IntentService
延遲執行。
2、使用SharedPreferences
來保存應用啟動需要的配置信息。
3、使用SingleTask
或SingleTop
啟動模式,避免創建多個實例。
public class InitService extends IntentService {
public InitService() {
super("InitService");
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
// 初始化耗時操作
}
}
六、布局優化
1、使用ViewStub
來延遲載入布局。
2、使用include
標籤重用相同布局。
3、使用merge
標籤來消除嵌套的布局。
4、使用ConstraintLayout
布局,避免使用RelativeLayout和LinearLayout。
// activity_main.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="@layout/view_header" />
<ViewStub
android:id="@+id/stub_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inflatedId="@+id/content"
android:layout="@layout/view_content" />
<include layout="@layout/view_footer" />
</LinearLayout>
// view_content.xml
<merge
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:id="@+id/text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
</merge>
原創文章,作者:FONT,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/131158.html