1.碎片的使用
- 建议引用support.v4包
- 事物替换
@Bind(R.id.leftfragment_btn) Button leftfragment_btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
ButterKnife.bind(this);
leftfragment_btn.setOnClickListener(this);
replaceFragment(new RightFragment());
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.leftfragment_btn:
replaceFragment(new AnotherRightFragment());
break;
}
}
private void replaceFragment(Fragment fragment) {
FragmentManager fragmentManager=getSupportFragmentManager();
FragmentTransaction transaction=fragmentManager.beginTransaction();
transaction.replace(R.id.right_layout,fragment);
transaction.addToBackStack(null); //碎片中模拟返回栈
transaction.commit();
}
2.碎片的生命周期
注:建立一个demo,进行碎片的替换,在生命周期函数中打印一下日志,即可明白;
public class RightFragment extends android.support.v4.app.Fragment {
private static final String TAG="RightFragment";
@Override
public void onAttach(Context context) {
super.onAttach(context);
Log.i(TAG,"onAttach");
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG,"onCreate");
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
Log.i(TAG,"onCreateView");
View view=inflater.inflate(R.layout.right_fragment,container,false);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.i(TAG,"onActivityCreated");
}
@Override
public void onStart() {
super.onStart();
Log.i(TAG,"onStart");
}
@Override
public void onResume() {
super.onResume();
Log.i(TAG,"onResume");
}
@Override
public void onPause() {
super.onPause();
Log.i(TAG,"onPause");
}
@Override
public void onStop() {
super.onStop();
Log.i(TAG,"onStop");
}
@Override
public void onDestroyView() {
super.onDestroyView();
Log.i(TAG,"onDestroyView");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG,"onDestroy");
}
@Override
public void onDetach() {
super.onDetach();
Log.i(TAG,"onDetach");
}
}
3. 限定符
- large限定符:res下新建一个layout-large资源文件夹,新建mainactivity.xml 在平板和手机上,会自动加载不同的对应的布局,完成适配,解决单双页判定。 限定符大小:small,normal,large,xlarge () ; 分辨率:ldpi, mdpi, hdpi, xhdpi ; 方向: land (横屏) ,port(竖屏);
- 最小宽度限定符:res下新建一个layout-sw600dp资源文件夹, 大于600dp加载此文件下的布局;小于600dp,加载默认的layout中的布局。