Android碎片fragment實現靜態載入的例項程式碼
阿新 • • 發佈:2020-01-07
靜態載入好後的介面如下,兩個碎片分別位於一個活動的左邊和右邊:
左邊和右邊分別為一個碎片,這兩個碎片正好將一整個活動佈滿。一個活動當中可以擁有多個碎片,碎片的含義就是可以在同一個UI介面下,將這個介面分成好幾個介面,並且可以分別更新自己的狀態,如果沒有碎片,那麼如果你想要單獨在某一個區域實現活動的“跳轉”就不可能了,因此我們可以引入碎片,這樣就可以在這個區域單獨進行碎片的跳轉。在利用底部標題欄進行首頁UI的切換的時候就需要用到碎片,因此碎片在安卓開發當中十分廣泛,這篇部落格將會與你講解如何實現靜態載入碎片,除了靜態載入碎片,還具有動態載入碎片的方式,兩種方式不同的方式都進行理解與引用,才可以把碎片的威力發揮到最大。下面是程式碼,第一個是主活動當中的程式碼,主活動一定得繼承Fragment這個類才可以實現碎片:
一.MainActivity.java
import androidx.fragment.app.FragmentActivity; import android.os.Bundle; import android.util.Log; public class MainActivity extends FragmentActivity { public MainActivity() { Log.e("TAG","MainActivity().."); } @Override protected void onCreate(Bundle savedInstanceState) { Log.e("TAG","MainActivity onCreate().."); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
然後咱們建立碎片,在上述的UI介面當中有兩個碎片的區塊,因此我們連續建立兩個碎片:
二.MyFragment.java
我們在這個碎片當中利用Java直接引入TextView控制元件,當然在這個碎片所對應的xml檔案當中也可以,這是相互等效的,都比較簡單。
import android.graphics.Color; import android.os.Bundle; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class MyFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) { //載入佈局得到View物件並返回 //建立一個檢視物件,設定資料並返回 TextView textView = new TextView(getActivity()); textView.setText("這是第一個碎片"); textView.setBackgroundColor(Color.RED); return textView; } }
三.MyFragment2.java
import android.graphics.Color; import android.os.Bundle; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class MyFragment2 extends Fragment { @Override public View onCreateView(LayoutInflater inflater,設定資料並返回 TextView textView = new TextView(getActivity()); textView.setText("這是第二個碎片"); textView.setBackgroundColor(Color.RED); return textView; } }
之後在咱們的主活動的UI介面當中將程式碼修改為:
四.activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" tools:context=".MainActivity"> <fragment android:name="com.example.fragment.MyFragment" android:id="@+id/myfragment_1" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent" /> <fragment android:name="com.example.fragment.MyFragment2" android:id="@+id/myfragment_2" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent" /> </LinearLayout>
這樣就可以把fragment引入到咱們的主活動上面來啦,執行安卓專案,大功告成!!
總結
以上所述是小編給大家介紹的在Android碎片fragment實現靜態載入的例項程式碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對我們網站的支援!
如果你覺得本文對你有幫助,歡迎轉載,煩請註明出處,謝謝!