Fragment
两种生成方式
静态生成碎片
public class LeftFragment extends Fragment{
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstatnceState){
View view=inflater.inflate(R.layout.right_fragment,container,false);
return view;
}
}
<LinearLayout xmlns:android=“http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="@+id/left_fragment"
android:name="com.example.fragmenttest.LeftFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"/>
</LinearLayout>
动态生成碎片
public class AnotherRightFragment extends Fragment{
public View onCreateView(Bundle savedInstanceState){
View view=inflater.inflate(R.layout.another_right_fragment,container,false);
return view;
}
}
public class MainActivity extends Activity implements OnClickListener{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button=(Button)findViewById(R.id.button);
button.setOnClickListener(this);
}
public void onClick(View view){
switch(view.getId()){
case R.id.button:
AnotherRightFragment fragment =new AnotherRightFragment();
FragmentManager manager=getFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();//开启一个事务
transaction.replace(R.id.right_layout,fragment);
transaction.commit();//提交事务
break;
}
}
}
碎片中模拟返回栈 FragmentTransaction中提供了一个addToBackStack()方法,可以将一个事务添加到返回栈中
public class MainActivity extends Activity implements OnClickListener{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
...
}
public void onClick(View view){
switch(view.getId()){
case R.id.button:
AnotherRightFragment fragment =new AnotherRightFragment();
FragmentManager manager=getFragmentManager();
FragmentTransaction transaction =manager.beginTransaction();
transaction.replace(R.id.right_layout,fragment);
transaction.addToBackStack(null); //此时碎片会进入到停止状态 没有调用的话,碎片就会进入销毁状态。
transaction.commit();
break;
}
}
}
这里我们在事务提交之前调用了FragmentTransaction的addToBackStack()方法,它可以接收一个名字用于描述返回栈的状态,一般传入null即可。现在重新运行程序,并点击按钮将AnotherRightFragment添加到活动中,然后按下Back键中,你会发现程序并没有退出,而是回到了RightFragment界面,再次按下Back键程序才会退出。
碎片和活动之间进行通信
FragmentManager提供了一个类似于findViewById()的方法,专门用于从布局文件中获取碎片的实例,代码如下所示:
RightFragment fragment =(RightFragment)getFragmentManager().findViewById(R.id.right_fragment);
获取到碎片的实例之后,就能轻松地调用碎片里的方法了。
在碎片中调用活动里的方法,在每个碎片中都可以通过调用getActivity()方法来得到和当前碎片相关联的活动实例:
MainActivity activity=(MainActivity)getActivity();
碎片与碎片之间的通信功能:首先在一个碎片中可以得到与它相关联的活动,然后通过这个活动去获取另外一个碎片的实例,这也就实现了碎片之间的通信功能。
Fragment限定符
最小限定符: