Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android Fragment的簡單使用

android Fragment的簡單使用

編輯:關於Android編程



public class DetailsFragment extends Fragment{
	private static final String[] WEEKS=new String[]{"a-1","b-1","c-1"};
	public static DetailsFragment newInstance(int index){
		DetailsFragment f = new DetailsFragment();
		Bundle b = new Bundle();
		b.putInt("index", index);
		f.setArguments(b);
		System.out.println("--==");
		return f;
	}
	public int getShowIndex(){
		int index = getArguments().getInt("index",0);
		return index;
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		TextView text = new TextView(getActivity());
		text.setText(WEEKS[getShowIndex()]);
		return text;
	}
}


public class FragmentAcitivity extends ListFragment{
	private static final String[] WEEKS=new String[]{"a","b","c"};
	//設置初始化選擇位置
	int mCurCheckPosition= 0;
	int mShownCheckPosition = -1;
	/**
	 * 填充數據
	 */
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		setListAdapter(new ArrayAdapter(getActivity(), 
				android.R.layout.simple_list_item_activated_1,
				android.R.id.text1,WEEKS));
		//創建之時默認選中行的詳細信息
		showDetals(mCurCheckPosition);
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		//手動選中某一行顯示該行的詳細信息
		showDetals(position);
	}
	/**
	 * 顯示詳細信息
	 * @param index 選中行
	 */
	public void showDetals(int index){
		//fragment的管理器
		FragmentManager am = getFragmentManager();
		DetailsFragment details = (DetailsFragment)am.findFragmentById(R.id.details);
		if(details == null || details.getShowIndex()!=index){
			//設置單選模式
			getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
			//指定條目被選中
			getListView().setItemChecked(index, true);
			details = DetailsFragment.newInstance(index);
			//新建新的DetailsFragment實例
			FragmentTransaction ft = am.beginTransaction();
			//替換FrameLayout為DetailsFragment
			ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
			//將得到的fragment替換當前ViewGroup內容,add則不替換會一次累加
			ft.replace(R.id.details, details);
			//提交
			ft.commit();
		}
	}

}




    
	<frameLayout 
	    android:id="@+id/details"
	    android:layout_weight="2"
	    android:layout_width="0dp"
	    android:layout_height="match_parent"
	    android:background="?android:attr/detailsElementBackground"/>




  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved