提高Android代碼復用性的幾種方式
對于初學者來說,當自己要實現相似的功能時候,總是復制粘貼。這樣不僅增加了工作量,同時也造成了代碼冗余等問題。下面,就由小言來介紹幾種提高Android代碼復用性的方法。(為了淺顯易懂,都是舉最簡單的例子,假如里面有什么不對的,敬請提出改善)
1、活用include
include中文翻譯是包含包括的意思。最直接明顯的運用的地方便是APP的標題,因為在一個APP中,其標題的格局差不多一致,每次都要復制粘貼,多麻煩。現在就來介紹一下include的簡單運用。
首先,我們先舉一個例子,例如在layout中創建一個名為include_title.xml的文件,其代碼為:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="50dp" android:background="@color/blue" > <ImageButton android:id="@+id/imgbtnback" android:layout_width="40dp" android:layout_height="fill_parent" android:background="@color/transparent" android:src="@drawable/fanhui" /> <TextView android:id="@+id/tvtitle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="標題" android:textColor="@color/white" android:textSize="20dp" /> </RelativeLayout>
然后在需要添加標題的xml文件中加上 <include layout="@layout/include_title" />這話便可將標題顯示在當前頁面中,例如:
<?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="match_parent" android:orientation="vertical" > <include layout="@layout/include_title" /> </LinearLayout>
2、使用extends
在一些頁面中,我們總是需要共用一些頁面顯示效果的功能,例如Toast,Dialog等等。在這時,我們可以將這些東西封裝到一個Activity中,當某個Activity需要使用里面的功能的時候,只要直接去繼承它們,然后調用相應的方法即可。以下為制作一個BaseActivity的例子代碼:
import android.app.Activity; import android.widget.Toast; public class BaseActivity extends Activity { /** * 彈出提示(int) * * @param intContent */ public void showToast(int intContent) { Toast.makeText(getApplication(), intContent, Toast.LENGTH_SHORT).show(); } /** * 彈出提示(String) * * @param intContent */ public void showToast(String strContent) { Toast.makeText(getApplication(), strContent, Toast.LENGTH_SHORT).show(); } }
當我們需要使用Toast的時候,只要繼承這個BaseActivity這個類,然后直接調用showToast(參數)方法便可以直接彈出Toast,是不是簡單一些呢。
3、類的封裝
在2中講的是將頁面顯示的效果封裝起來,而這里講的是將功能代碼封裝起來。在一些時候,我們需要重復調用一個功能方法,是不是覺得復制粘貼很麻煩呢,在這時,我們只需要將其功能代碼封裝起來,供以后調用。這也就是MVC模式中的Model層。例如:
我們新建一個名為Tools的Java類,其代碼為:
/** * 工具類 * */ public class Tools { public static void outPut(Object obj) { System.out.println(obj); } }
4、使用string.xml和color.xml
開發一個APP的時候,我們難免會使用到一些顏色值或者文字,在這時,我們應該將其放在相對應的color.xml或string.xml文件中,這樣不僅提高代碼的復用性,而且也便于修改,而不用到時改點需求的時候,就要到處找出頁面修改其顏色值和文字。
例如:color.xml文件
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="transparent">#00000000</color> <color name="black">#000000</color> <color name="blue">#5DC0F8</color> </resources>
使用的時候:
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="標題" android:textColor="@color/blue" />
string.xml的就不舉例了,估計大家都懂了。
5、使用library
當做項目做多的時候,就會發現,其實,很多功能或者效果什么的,都非常相似,在這時,我們就該收集一下那些基本代碼,將其封裝在一個library中,等到用時直接加載這個library,而不需要重新寫。其實就是和導入開源框架一樣。