今天跟大家分析個人對fragment用法的理解
1.Fragment起源
迄今為止,android的設(shè)備越來越多,大到智能平板和電視,小到手機(jī)甚至是智能手表,這些設(shè)備因為px的不同而需要針對各種機(jī)型進(jìn)行適配,而fragment最初在Android3.0出就是針對平板的,在到4.0的時候就開始和手機(jī)整合使得Android的app能運(yùn)行各種各樣的屏幕上.而且fragment的動態(tài)改變也使得大多數(shù)開發(fā)者對它情有獨鐘,使用fragment的應(yīng)用也越來越多,下面就跟大家粗略的介紹一下fragment的用法以及生命周期在不同的情況會發(fā)生怎樣的變化.
2.Fragment的生命周期
大部分人一談到fragment的生命周期,肯定是先上一張跟Activity一樣惡心的圖片,先不說新手能不能記清楚上面的是一個個生命周期方法,單單是英文就惡心到當(dāng)初看它的我了.不過,我還是得上這么一張圖片詳細(xì)解釋一下為何有這么多的生命周期,這些生命周期又是在什么時候調(diào)用的.
因為Fragment是依附于Activity的所以多了一個onActivityCreated(Bundle)方法,該方法是在依附的Activity的onCreate()方法調(diào)用返回之后開始調(diào)用的,而其他的10個方法則是上下對應(yīng) 所以大家只用理解性的記憶前6個方法 后面的方法就是除了onActivityCreated()相反的對應(yīng)方法.如下:
onAttach() --- onDetach()
onCreate() --- onDestroy()
onCreateView() --- onDestroyView()
onStart() --- onStop()
onResume() --- onPause()
3.Fragment的創(chuàng)建
Fragment是依附于Activity的,所以你要使用Fragment你就必須要有Activity,話不多說直接擼代碼.
3.1 Fragment4Code
通過代碼的方式在Activity載入Fragment
//R.id.container 為Activity的布局文件中的占位容器
getFragmentManager()
.beginTransaction() //事務(wù)
.addToBackStack(null) //回退棧
//.replace(R.id.container, new FirstFragment()) 替換
.add(R.id.container, new FirstFragment()) //添加
.commit(); //提交
3.2 Fragment4XML
通過XML直接添加
<fragment
android:id="@+id/fragment" //id
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="packageName.FirstFragment"/>
4.Fragment回退棧
通過回退棧,讓用戶點擊回退鍵的時候先將棧內(nèi)fragment彈棧后再退出
//創(chuàng)建第一個fragment
public class frangment_fir extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return View.inflate(getActivity(), R.layout.fragment_item, null);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Button bt_1 = (Button) view.findViewById(R.id.bt_1);
bt_1.setOnClickListener(new View.OnClickListener() {
//**設(shè)置點擊監(jiān)聽 添加加入到回退棧的fragment_sec**
@Override
public void onClick(View v) {
getFragmentManager()
.beginTransaction()
.addToBackStack(null) //將fragment_sec加入到默認(rèn)的回退棧中
.replace(R.id.container, new frangment_sec())
.commit();
}
});
}
}
//創(chuàng)建第二個fragment
public class frangment_sec extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return View.inflate(getActivity(), R.layout.fragment_item_sec, null);
}
}
//在MainActivity 添加fragment_fir;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getFragmentManager()
.beginTransaction()
.add(R.id.container, new frangment_one())
.commit();
}
}
需要補(bǔ)充的是:
當(dāng)fragment_sec是回退棧添加的時候 再次按下回退鍵的時候,**fragment_fir不走onAttach(),onCreate(),onDestroy(),onDetach()這幾個方法 **,所以使用的時候可以根據(jù)需求將一次加載數(shù)據(jù)方法放入其中,而多次加載數(shù)據(jù)方法規(guī)避這幾個方法.
5.Fragment與Activity之間的通訊
5.1點擊切換fragment
通過點擊不同RadioGroup中的button來切換Fragment
public class MainActivity extends Activity implements OnCheckedChangeListener {
private RadioGroup rg;
private List<Fragment> fragments;
private int preIndex;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rg = (RadioGroup) findViewById(R.id.rg);
rg.setOnCheckedChangeListener(this);
initData();
}
//初始化添加三個不同fragment到集合中
private void initData() {
fragments = new ArrayList<>();
fragments.add(new Fragment1());
fragments.add(new Fragment2());
fragments.add(new Fragment3());
}
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.rb1:
changeFragment(0);
break;
case R.id.rb2:
changeFragment(1);
break;
case R.id.rb3:
changeFragment(2);
break;
default:
break;
}
}
//定義改變fragment的方法 當(dāng)點擊不同fragment對應(yīng)的raidobutton時候進(jìn)行切換
private void changeFragment(int index) {
Fragment fragment = fragments.get(index);
FragmentTransaction ft = getFragmentManager().beginTransaction();
if (!fragment.isAdded()) {
ft.add(R.id.container, fragment);
}
ft.hide(fragments.get(preIndex));
ft.show(fragment);
ft.commit();
preIndex = index;
}
}
5.2 :Fragment2Activity(最早的方法,不推薦使用)
下列代碼可以用接口回調(diào)實現(xiàn)(接口回調(diào)被放在5.2.2中實fragment2fragment)
public class MainActivity extends Activity {
private Button bt_activity;
private Myfragment fragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt_activity = (Button) findViewById(R.id.bt_activity);
}
public void click(View view) {
if (fragment == null ) {
fragment = new Myfragment();
Bundle args = new Bundle();
args.putString("key", "Activity2Fragment");
fragment.setArguments(args);
getFragmentManager().beginTransaction().addToBackStack(null)
.add(R.id.container, fragment).commit();
}
}
public void transformGift(String text) {
bt_activity.setText(text);
}
}
public class Myfragment extends Fragment {
private View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (view == null) {
view = View.inflate(getActivity(), R.layout.fragment_item,
null);
}
return view;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Bundle bundle = getArguments();
final String string = bundle.getString("key");
Button bt = (Button) view.findViewById(R.id.bt);
bt.setText(string);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//通過獲取依附的Activity進(jìn)行強(qiáng)轉(zhuǎn)調(diào)用(耦合性太強(qiáng),不推薦使用)
((MainActivity) getActivity()).transformGift("Fragment2Activity");
}
});
}
}
5.3 :接口回調(diào)實現(xiàn)Fragment2Fragment
使用接口回調(diào)來實現(xiàn)依附在同一個Activity的Fragment之間的通訊.
將2個fragment放入mainActivity兩個平分容器中.
//左邊的Fragment
public class Fragment_left extends Fragment implements OnItemClickListener {
private ListView ll_left;
private String[] item ="XXX,XXX,XXX,XXX,XXX".split(","); // 具體名字忽略.
private OnGetResultListener listener;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return View.inflate(getActivity(), R.layout.left_item, null);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ll_left = (ListView) view.findViewById(R.id.ll_left);
ll_left.setAdapter(new ArrayAdapter<>(getActivity(),
android.R.layout.simple_list_item_1, item));
ll_left.setOnItemClickListener(this);
}
public void setOnGetResultListener(OnGetResultListener listener) {
this.listener = listener;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
if (listener != null) {
listener.onGetResult(item[position]);
}
}
}
//右邊的fragment
public class Fragment_right extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return View.inflate(getActivity(), R.layout.right_item, null);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Bundle bundle = getArguments();
if (bundle != null) {
String string = bundle.getString("data");
((TextView) view.findViewById(R.id.tv)).setText(string+"灰常漂亮!!!");
}
}
}
//MainActivity 用于充當(dāng)fragment交互的橋梁
public class MainActivity extends Activity implements OnGetResultListener {
private Fragment_left fragment_left;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Fragment_left = new Fragment_left();
fragment_left.setOnGetResultListener(this);
getFragmentManager().beginTransaction()
.replace(R.id.left_container, fragment_left)
.replace(R.id.right_container, new fragment_right()).commit();
}
@Override
public void onGetResult(String string) {
Fragment_right fragment = new Fragment_right();
Bundle args = new Bundle();
args.putString("data", string);
fragment.setArguments(args);
getFragmentManager().beginTransaction()
.replace(R.id.right_container, fragment).commit();
}
}
5.4 :使用otto框架(Bus)
使用前導(dǎo)入otto的jar包并單例Bus
// 單例Bus
import com.squareup.otto.Bus;
public class busFactory {
public static Bus bus = new Bus();
private busFactory() {
}
public static Bus getBus() {
return bus;
}
}
//左邊的Fragment
public class Fragment_left extends Fragment implements OnItemClickListener {
private ListView ll_left;
private String[] item = "碧瑤,陸雪琪,小龍女,李莫愁,王語嫣,李滄海,趙敏,周芷若,小昭,鷹離".split(",");
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return View.inflate(getActivity(), R.layout.left_item, null);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ll_left = (ListView) view.findViewById(R.id.ll_left);
ll_left.setAdapter(new ArrayAdapter<>(getActivity(),
android.R.layout.simple_list_item_1, item));
ll_left.setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Bus bus = busFactory.getBus();
bus.post(item[position]);
}
}
//右邊Fragment
public class Fragment_right extends Fragment {
private TextView tv;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
busFactory.getBus().register(this); //注冊
return View.inflate(getActivity(), R.layout.right_item, null);
}
@Override
public void onDestroy() {
super.onDestroy();
busFactory.getBus().unregister(this); //注銷
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
tv = (TextView) view.findViewById(R.id.tv);
}
@Subscribe //注解來實現(xiàn)數(shù)據(jù)傳遞
public void setData(String text) {//參數(shù)可以是Bus.post傳入?yún)?shù)的類型或者父類類型(Object);
tv.setText(text + "text");
}
}
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getFragmentManager().beginTransaction()
.replace(R.id.left_container, new Fragment_left())
.replace(R.id.right_container, new Fragment_right()).commit();
}
}
總結(jié):
其實開發(fā)中用到的時候大多數(shù)都是用的接口回調(diào)或者otto ,但是個人在開發(fā)中發(fā)現(xiàn)用接口回調(diào)的時候,會出現(xiàn)畫面數(shù)據(jù)重疊Bug.而用EventBus就可以避免了這類Bug,所以推薦大家在使用的時候最好還是使用Bus來進(jìn)行通訊.