我们可以这样做:
存在相对布局的活动类。让该相对布局(mParentLayout)成为活动视图层次结构的根元素。并且要添加到相对布局的片段将是 mGridFragment,位于 Button (mGridBtn) 下方的位置。
public class DroidOpsActivity extends FragmentActivity implements
OnClickListener {
private RelativeLayout mParentLayout = null;
private Button mGridBtn = null;
private FragmentManager mFragmentMgr = null;
private FragmentTransaction mFragmentTransc = null;
private Fragment mGridFragment = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initialize();
}
private void initialize() {
setContentView(R.layout.activity_droid_ops);
mParentLayout = (RelativeLayout) findViewById(R.id.parent_layout);
mGridBtn = (Button) findViewById(R.id.grid_button);
mFragmentMgr = getSupportFragmentManager();
registerListener();
}
private void registerListener() {
mGridBtn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.grid_button:
loadFragment();
mGridBtn.setEnabled(false);
break;
}
}
private void loadFragment() {
mGridFragment = new DroidOpsFragments();
mFragmentTransc = mFragmentMgr.beginTransaction();
mFragmentTransc.add(mParentLayout.getId(), mGridFragment);
mFragmentTransc.addToBackStack(null);
mFragmentTransc.commit();
}
public RelativeLayout.LayoutParams fetchLayoutParams() {
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
// We can add any rule available for RelativeLayout and hence can position accordingly
params.addRule(RelativeLayout.BELOW, mGridBtn.getId());
return params;
}
}
相应的 Fragment 类,将在 Activity 的布局中定位。
public class DroidOpsFragments extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.view_word_grid, null);
// Here we are fetching the layoutParams from parent activity and setting it to the fragment's view.
view.setLayoutParams(((DroidOpsActivity) activity).fetchLayoutParams());
return view;
}
}