Fragment 静态注册
xml
...
<fragment
android:id="@+id/fragment_static"
android:name="com.example.study_android.fragment.StaticFragment"
android:layout_width="match_parent"
android:layout_height="60dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="主要内容" />
...
java
public class StaticFragment extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_static, container, false);
}
}
Fragment 动态注册
在某些 Adapter 中返回一个一个 Fragment
java
public class DynamicFragment extends Fragment {
public static DynamicFragment newInstance(int position,String name, String desc) {
DynamicFragment fragment = new DynamicFragment();
Bundle args = new Bundle();
args.putInt("position", position);
args.putString("name", name);
args.putString("desc", desc);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
/*
* container:fragment根据该容器计算宽高
* false:是否将该fragment添加到container容器中
* */
View view = inflater.inflate(R.layout.fragment_dynamic, container, false);
Bundle arguments = getArguments();
if (arguments != null) {
TextView name = view.findViewById(R.id.name);
TextView desc = view.findViewById(R.id.desc);
name.setText(arguments.getString("name"));
desc.setText(arguments.getString("desc"));
}
return view;
}
}