Android Api Demos登頂之路(四十)Fragment-->Layout

來源:互聯網
上載者:User

標籤:apidemo   layout   listfragme   fragment   布局   

這個demo示範了fragment的布局特點。本例中在豎屏的狀態下,當我們點擊列表的條目時 打一個activity來顯示這個條目的詳細資料。
* 而在橫屏的狀態下由於螢幕足夠寬,我們就在介面上同時顯示了兩個fragment,一個用來 顯示標題,另一個用來顯示詳細資料。
layout目錄下建立豎屏顯示的布局檔案:fragment_layout.xml

<?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent" >    <fragment         class="com.fishtosky.fragmentlayout.MainActivity$TitlesFrament"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:id="@+id/titles_fragment"/></FrameLayout>

在res目錄下建立layout-land檔案夾,在該檔案夾下建立橫屏顯示的布局檔案,這裡需要注意的是必須與layout目錄下的布局檔案名稱字相同。fragment_layout.xml

<?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         class="com.fishtosky.fragmentlayout.MainActivity$TitlesFrament"        android:layout_width="0dp"        android:layout_height="match_parent"        android:id="@+id/titles_fragment"        android:layout_weight="1"/>    <FrameLayout         android:layout_width="0dp"        android:layout_height="match_parent"        android:layout_weight="2"        android:id="@+id/details_framelayout">    </FrameLayout></LinearLayout>

MainActivity

public class MainActivity extends Activity {    private static String[] title = new String[] { "title1", "title2",            "title3", "title4", "title5" };    private static String[] details = new String[] { "標題一的詳細資料", "標題二的詳細資料",            "標題三的詳細資料", "標題四的詳細資料", "標題五的詳細資料" };    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.fragment_layout);    }    // 定義顯示詳細資料的activity    public static class DetialsActivity extends Activity {        @Override        protected void onCreate(Bundle savedInstanceState) {            super.onCreate(savedInstanceState);            // 如果是橫屏狀態則直接結束            if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {                finish();                return;            }            if(savedInstanceState==null){                DetialsFrtagment df=new DetialsFrtagment();                df.setArguments(getIntent().getExtras());                getFragmentManager().beginTransaction().add(android.R.id.content, df).commit();            }        }    }    /*     * 定義一個繼承listFragment的類,用於顯示內容的標題列表     */    public static class TitlesFrament extends ListFragment {        // 定義一個布爾型變數,用於控制是否同時顯示兩個Fragment        private boolean mDualPane;        // 定義當前選中的條目的序號        private int mCurrentChoiceItem;        /*         * activity 建立完畢後調用此方法         */        @Override        public void onActivityCreated(Bundle savedInstanceState) {            super.onActivityCreated(savedInstanceState);            // 設定listView的資料配接器            setListAdapter(new ArrayAdapter<String>(getActivity(),                    android.R.layout.simple_list_item_activated_1, title));            // 找到用於顯示詳細資料的組件            FrameLayout fl = (FrameLayout) getActivity().findViewById(                    R.id.details_framelayout);            /*             * 判斷一下該組件是否是空且是否處於可見狀態,如果為true則表示當前處於橫屏模式,可以同時             * 顯示標題和詳細資料兩個fragment。如果為false則表明當前是處于堅屏狀態下,只能顯示             * 標題的fragment,通過點擊標題的條目開啟另一個activity來顯示詳細資料             */            mDualPane = fl != null && fl.getVisibility() == View.VISIBLE;            if (savedInstanceState != null) {                mCurrentChoiceItem = savedInstanceState.getInt("currentChoice",                        0);            }            if (mDualPane) {                // 設定列表為單選模式,當使用者一選中某一條目時,該條目將會一直處於高亮狀態                getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);                showDetails(mCurrentChoiceItem);            }        }        /*         * 用於顯示第個條目的詳細資料         */        private void showDetails(int index) {            mCurrentChoiceItem = index;            if (mDualPane) {                // 設定選中的條目為選中狀態,呈現高亮顯示                getListView().setItemChecked(index, true);                // 判斷當前顯示的fragment並替換                DetialsFrtagment df = (DetialsFrtagment) getFragmentManager()                        .findFragmentById(R.id.details_framelayout);                // 如果選中新的條目,或者初始化資料                if (df == null || df.getShowIndex() != index) {                    DetialsFrtagment newFragment = DetialsFrtagment                            .getInstance(mCurrentChoiceItem);                    FragmentTransaction ft = getFragmentManager()                            .beginTransaction();                    // 設定切換動畫                    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);                    ft.replace(R.id.details_framelayout, newFragment);                    ft.commit();                }            } else {                // 如果不是同時顯示title和details視窗,則開啟一個新activity                Intent intent = new Intent(getActivity(), DetialsActivity.class);                intent.putExtra("index", index);                startActivity(intent);            }        }        @Override        public void onSaveInstanceState(Bundle outState) {            super.onSaveInstanceState(outState);            outState.putInt("currentChoice", mCurrentChoiceItem);        }        @Override        public void onListItemClick(ListView l, View v, int position, long id) {            super.onListItemClick(l, v, position, id);            showDetails(position);        }    }    public static class DetialsFrtagment extends Fragment {        public static DetialsFrtagment getInstance(int index) {            DetialsFrtagment df = new DetialsFrtagment();            Bundle args = new Bundle();            args.putInt("index", index);            df.setArguments(args);            return df;        }        public int getShowIndex() {            return getArguments().getInt("index");        }        @Override        public View onCreateView(LayoutInflater inflater, ViewGroup container,                Bundle savedInstanceState) {            /*             * 當手機處於橫屏狀態下,正常顯示兩個fragment,而切換到堅屏模式後,系統會儲存當前             * 的UI資訊,並重新繪製UI。從savedInstanceState從中恢複UI資訊,此時detailFragment             * 會被建立,但我們在堅屏模式下不顯示詳細資料的表單,所以此時不需要去建立detailFragment             * 的視圖,所以可能通過container是否為空白來控制是否顯示View。             */            if (container == null) {                return null;            }            // 只有在需要建立並返回視圖的地方才執行下面的代碼            ScrollView sv = new ScrollView(getActivity());            TextView tv = new TextView(getActivity());            int padding = (int) TypedValue.applyDimension(                    TypedValue.COMPLEX_UNIT_DIP, 5, getActivity()                            .getResources().getDisplayMetrics());            tv.setPadding(padding, padding, padding, padding);            sv.addView(tv);            tv.setText(details[getShowIndex()]);            return sv;        }    }}

配置activity

</activity>        <activity android:name="com.fishtosky.fragmentlayout.MainActivity$DetialsActivity"></activity>

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

Android Api Demos登頂之路(四十)Fragment-->Layout

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.