Fragment学习
Fragment可以看作是一种轻量级的Activity,它像Activity一样具有生命周期,也可以有自己的布局和输入事件,但是它比Activity更加灵活。Fragment的目的是适配不同终端屏幕分辨率,确保软件在不同终端上都有良好的用户体验。
本文实现了Fragment的基本使用和动态切换。
1.定义Fragment类(extends Fragment)和对应的布局文件,将Fragment对应的view绑定上(如果有的话)。这里app.Fragment和v4.app.Fragment好像在效果上没啥区别,由于我更在意基本的使用,也没细看文档里的差别。
2.在主函数中定义点击事件用来动态切换fragment。
代码如下:
1.三个Fragment,AboveFragment生成上方Fragment,BelowFragment生成下方Fragment,SecondAboveFragment是点击事件发生时切换到新的Fragment。
package com.bupt.markfavor.demo0916fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by markfavor on 2017/9/16.
*/
public class AboveFragment extends Fragment{
public static AboveFragment instance = new AboveFragment();
public static AboveFragment getInstance(){
return instance;
}
private TextView myTextView;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout_above,container,false);
myTextView = (TextView) view.findViewById(R.id.tv1);
return view;
}
}
package com.bupt.markfavor.demo0916fragment;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by markfavor on 2017/9/16.
*/
public class BelowFragment extends Fragment {
private TextView myTextView;
public static BelowFragment instance=new BelowFragment();
public static BelowFragment getInstance(){
return instance;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGro