Android常用複雑コントロール使用(三)--Fragment


Android方面の文章が出てくるのは久しぶりで、今日はちょうどインタフェース方面のものを書く時間がありました.
Fragmentの意味は「破片」であり、AndroidではFragmentは単独では使用できず、あるActivityに埋め込まなければならない.次に、Tab切り替えの下部メニューバーの例を見て、Fragmentがどのように使用されているかを見てみましょう.
1.準備
FragmentはAndroid 3.0以降に提案された概念で、私たちのプロジェクトは携帯電話で実行することを望んでいます.Android 4.0のプロジェクトを構築する必要があります.
また、私はプロジェクトでxUtilsツールクラス(これは実用的なツールクラスで、後で単独でシリーズを開いて説明します)を大量に使用しているので、libファイルをclasspathに追加する必要があります.
2. AndroidManifest.xml
これは簡単です.主にxUtilsで使用する権限を追加します.
    <!--      , xUtils   -->
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

3.リソースの準備
私たちが準備しなければならないリソースは主に以下のとおりです.
3.1ピクチャボタンファイル
ここではicon 1~4,iconを用意しましたon 1~4の2組の4つのボタンの押下と弾き上げの画像.
3.2背景選択器
Androidにはバックグラウンドセレクタという特殊なタイプのリソースxmlファイルがあり、ボタンごとの様々な状態をそれぞれ定義することができます.以下のいずれかのselectorです.
<?xml version="1.0" encoding="utf-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/icon_1"  android:state_selected="true"/>
    <item android:drawable="@drawable/icon_on_1"/>
</selector>
他の3つのファイルは同様で、res/drawableディレクトリにすべて配置されます.
3.3 Activityレイアウト
プライマリActivityのレイアウトは次のとおりです.
<?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:background="@color/gray"
    android:orientation="vertical" >

<!-- Frame  ,  TabHost  Frame   -->
    <FrameLayout
        android:id="@+id/main_fragmentContainer"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:background="@color/white"
        android:layout_weight="1"/>
<!--       -->
    <android.support.v4.app.FragmentTabHost
        android:id="@+id/main_fragmenttabhost"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </android.support.v4.app.FragmentTabHost>
</LinearLayout>

簡単ですよね?FrameLayoutはFragmentのコンテナとして使用され、FragmentTabHostにツールバーボタンが格納されます.
3.4ナビゲーションバーボタンレイアウト
ここではナビゲーションバーのレイアウトを省略しました.必要ならandroid.support.v4.app.FragmentTabHostの内部にLayoutコントロールを追加して実現します.
ナビゲーションバーボタンのレイアウトは次のとおりです.
<?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:gravity="center"
              android:orientation="vertical">

    <!--     TextView       tv.setCompoundDrawables       
    <TextView
                android:id="@+id/tabButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@color/textgray"
                android:textSize="12sp"
                android:clickable="false"
                android:background="@android:color/transparent"
                android:gravity="center"
                />
                -->
		<ImageView android:id="@+id/tabImage"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingTop="10dip"
                android:contentDescription="@string/app_name" />
        <Button
                android:id="@+id/tabButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@color/textgray"
                android:textSize="12sp"
                android:clickable="false"
                android:background="@android:color/transparent"
                android:gravity="center"/>
</LinearLayout>

3.5 res/values
res/valuesの下には、次のリソースファイルがあります.
3.5.1 color.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="gray">#484848</color>
    <color name="white">#FFFFFF</color>
    <color name="black">#000000</color>
    <color name="textgray">#8f8f8f</color>
    <color name="background">#00FF00</color>
</resources>

3.5.2 strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">FragmentActivityDemo</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <!-- activity_main -->
    <string name="tab_1">Tab1</string>
    <string name="tab_2">Tab2</string>
    <string name="tab_3">Tab3</string>
    <string name="tab_4">Tab4</string>

</resources>

4.Javaソース
4.1 Fragmentコード
Fragmentコードは非常に簡単で、Activityとは少し異なり、FragmentとonCreateViewの書き換え方法から継承する必要があります.
public class Fragment1 extends Fragment {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		//             view
        View view = inflater.inflate(R.layout.fragment_1, container, false);
        //  view    ViewUtils     (xUtils  )
        ViewUtils.inject(this, view);

		return view;
	}

4.2 Activityコード
Activityのコードはやや複雑ですが、主に初期化時にTabを作成し、Fragmentを埋め込みます.
@ContentView(R.layout.activity_main)
public class MainActivity extends FragmentActivity {
	@ViewInject(R.id.main_fragmenttabhost)
	private FragmentTabHost main_tabhost;

	@SuppressWarnings("rawtypes")
	private Class fragmentClasses[] = { Fragment1.class, Fragment2.class,
			Fragment3.class, Fragment4.class };
	//   Tab  icon      /drawable      xml   
	private int tabIconRes[] = { R.drawable.tab_icon_1, R.drawable.tab_icon_2,
			R.drawable.tab_icon_3, R.drawable.tab_icon_4 };	
	private int tabTextRes[] = { R.string.tab_1, R.string.tab_2,
			R.string.tab_3, R.string.tab_4 };

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//   
		ViewUtils.inject(this);

		initTabs();
	}

	private void initTabs() {
		//   Frame     
		main_tabhost.setup(this, getSupportFragmentManager(),
				R.id.main_fragmentContainer);

		for (int i = 0; i < fragmentClasses.length; i++) {
			//      Tab  
			TabHost.TabSpec tabSpec = main_tabhost.newTabSpec(getString(tabTextRes[i]))
					.setIndicator(getTabItemView(i));
			main_tabhost.addTab(tabSpec, fragmentClasses[i], null);
			main_tabhost
					.getTabWidget()
					.getChildAt(i)
					.setBackgroundResource(
							R.drawable.selector_navbar_background);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	private View getTabItemView(int i) {
		LayoutInflater layoutInflater = LayoutInflater.from(this);
		View view = layoutInflater.inflate(R.layout.tabbar_item, null);

		Resources res = this.getResources();
		
		//       
		Button btn = (Button) view.findViewById(R.id.tabButton);
		btn.setText(res.getText(tabTextRes[i]));
		//    TextView          Image,     ImageView
//		Drawable drawable = res.getDrawable(tabIconRes[i]);
//		Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.tab_icon_sample);
//		drawable.setBounds(0, 0, bmp.getWidth(), bmp.getHeight());
//		btn.setCompoundDrawables(null, drawable, null, null);
		
		ImageView img = (ImageView) view.findViewById(R.id.tabImage);
		img.setImageResource(tabIconRes[i]);
		
		return view;
	}
}