Android學習——Fragment靜態加載


從今天開始做一套安卓的學習筆記,開發環境是Android Studio,把學習過程中的知識和遇到的問題都寫在這里,先從Fragment開始學起。

Fragment概述


Fragment是Android3.0之后引入的全新的概念,主要目的是用於大屏幕設備上,例如平板電腦。簡單來說,就我的個人理解,Fragment相當於一個一個集成好的裝飾品,可以用來裝飾Activity。而在Activity的空間變化了之后,只需要更改裝飾品的擺放位置即可,而無需重新修改具體的一個個零件。如下圖所示,當一個適用於平板的應用需要適用於手機時,只需要把不同的Fragment加載到不同的Activity中即可,而無需大改布局空間。

 

Fragment靜態加載


 

靜態加載,顧名思義,就是在布局文件中直接加載Fragment。在XML文件中,利用Fragment標簽即可實現靜態加載Fragment。

layout文件如下:

<fragment
        android:id="@+id/fragment1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:name="com.example.administrator.fragment.Fragment1"/>

 其中,name對應自己寫的Fragment類,id對應該fragment控件的唯一表示,不可為空,否則會報錯。

 

對應的Fragment1類必須繼承Fragment類,並在onCreateView中實現其與layout文件的對應:

public class Fragment1 extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_1,container,false);
        return view;
    }
}

 

可以在加載Fragment的Activity中,直接與FindViewByID方法來獲取Fragment的layout下對應的控件:

private void init() {
        mbutton= (Button) findViewById(R.id.button2);
        mtv= (TextView) findViewById(R.id.textview);
        mbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mtv.setText("轉換成功");
            }
        });
    }

 

總結起來就是:

1.創建Fragment類並實現對應的layout文件

2.在Activity的layout文件中添加Fragment控件,並與創建好的類關聯

 

遇到的問題


在實現Activity的時候,要注意重載的onCreate方法是protect的,而不是public的,否則會無法加載對應的layout文件。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM