android Fragment的简单使用
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<String>(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(); } } }
<?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="horizontal" > <fragment android:id="@+id/titles" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" class="com.example.fragment.FragmentAcitivity"/> <FrameLayout android:id="@+id/details" android:layout_weight="2" android:layout_width="0dp" android:layout_height="match_parent" android:background="?android:attr/detailsElementBackground"/> </LinearLayout>
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。