需求:
如果一個應用程序中有許多activity都會用到比如說titlebar,或者footerbar
這種情況下,架構的時候就可以定義一個BaseActivity了
思路是:
通過BaseActivity繼承Activity,在layout中為後面要添加的layout預留一個空的layout,具體代碼:
- public class BaseActivity extends Activity {
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- requestWindowFeature(Window.FEATURE_NO_TITLE);
- setContentView(R.layout.base);
- }
-
- public void baseSetContentView(int layoutResId) {
- LinearLayout llContent = (LinearLayout) findViewById(R.id.content);
- LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- View v = inflater.inflate(layoutResId, null);
- llContent.addView(v);
- }
-
- }
base布局文件:
- <?xml version="1.0" encoding="utf-8"?>
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:Android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent" >
-
- <LinearLayout
- android:layout_width="fill_parent"
- android:layout_height="50dip"
- android:background="@drawable/titlebar"
- android:layout_alignParentTop="true"
- android:orientation="horizontal" >
-
- <Button
- android:id="@+id/titlbarback"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/back"
- android:textSize="14dip" />
-
- <TextView
- android:id="@+id/title"
- style="@style/titlebarstyle"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/app_name" />
-
- <Button
- android:id="@+id/confirm"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/confirm"
- android:textSize="14dip" />
-
- <Button
- android:id="@+id/cancel"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/cancel"
- android:textSize="14dip" />
- </LinearLayout>
-
- <LinearLayout
- android:layout_width="fill_parent"
- android:layout_height="match_parent"
- android:id="@+id/content">
- </LinearLayout>
-
- </RelativeLayout>
這樣,當BaseActivity的子activity只要調用baseSetContentView這個方法把自己的layout設置一下就可以了。
更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11