1. 程式人生 > >Fragment動態新增控制元件(Button/Layout/...)

Fragment動態新增控制元件(Button/Layout/...)

最近在研究Andriod5.0系統Settings原始碼的修改,從主介面進去Settings中大部分都是使用Fragment,Fragment的頁面修改是通過重修onCrearteCiew()方法來實現的,下面是我把View的高度修改為800畫素,預留部分空間來新增其他的控制元件,例子Button,Layout等等

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = super
.onCreateView(inflater, container, savedInstanceState); /*定義LayoutParams 為了獲得當前View的屬性*/ ViewGroup.LayoutParams lpLayoutParams = rootView.getLayoutParams(); //設定View的高度,也可以設定其他屬性 lpLayoutParams.height = 800; rootView.setPadding(50, 50, 50, 50); //LayoutParams 屬性賦予Fragment當前的View
rootView.setLayoutParams(lpLayoutParams); return rootView; }

通過重寫onActivityCreated,自己定義了一個RelativeLayout ,並且在RelativeLayout 中新增Button

@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //定義了一個RelativeLayout ,LayoutParams 是控制元件屬性
        FrameLayout.LayoutParams
returnLayoutparams = new FrameLayout. LayoutParams(LayoutParams.MATCH_PARENT, h_buttonscreen); returnLayoutparams.gravity = Gravity.BOTTOM|Gravity.RIGHT; RelativeLayout returnLayout = new RelativeLayout(getActivity()); returnLayout.setPadding(50, 10, 50, 50); //這裡是我自己背景資源 returnLayout.setBackgroundResource(R.drawable.beijing); //定義了一個Button, FrameLayout.LayoutParams returnButtonparams = new FrameLayout.LayoutParams (LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); final Button returnbutton = new Button(getActivity()); returnbutton.setBackgroundResource(R.drawable.flst_return_button); returnbutton.setLayoutParams(returnButtonparams); //Layout中新增Button returnLayout.addView(returnbutton); //View中新增layout getActivity().addContentView(returnLayout, returnLayoutparams); returnbutton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO 自動生成的方法存根 Toast.makeText(getActivity(), "返回", Toast.LENGTH_LONG).show(); } }); }

//這樣你的Fragment頁面就可以根據自己需求來寫。
修改頁面,就得知道螢幕的大小,這樣的話,你可以更好的來佈局頁面,通過以下程式碼可以實現獲得螢幕寬度和高度

        DisplayMetrics dm =getResources().getDisplayMetrics();  
        int w_screen = dm.widthPixels;  
        int h_screen = dm.heightPixels;  

以上純屬個人理解,如有誤區,請指出