2012年1月16日星期一

Android 3.0 新增的片段(Fragment)

Android 3.0 新增片段(Fragment), 可以理解為類似嵌入活動(activity)內的一個子活動.

這是一個簡單的例子:

Android 3.0 新增的片段(Fragment)

在Eclipse創建一個新項目, Android3Frag; 要注意是: 建設目標(Build Targe)必須是 Android 3.0 (API Level 11)或更高.

先通過擴展 Fragment 創建一個 MyFragment 類, 並且重寫onCreateView()方法. 這便是我們的片段(Fragment).
package com.android3Frag;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;


public class MyFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Context context = getActivity().getApplicationContext();
LinearLayout layout = new LinearLayout(context);
TextView text = new TextView(context);
text.setText("FRAGMENT HERE");

ImageView image = new ImageView(context);
image.setImageDrawable(getResources().getDrawable(R.drawable.ic_launcher));

layout.addView(text);
layout.addView(image);

return layout;
}

}


修改佈局, main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >

<TextView
android:layout_width="0px"
android:layout_weight="2"
android:layout_height="match_parent"
android:text="@string/hello"/>
<fragment
class="com.android3Frag.MyFragment"
android:id="@+id/myfragment"
android:layout_width="0px"
android:layout_weight="3"
android:layout_height="match_parent"/>

</LinearLayout>



相關文章:
- 通過XML文件, 創建片段(Fragment)

沒有留言:

發佈留言