Android Fragment的使用 六 适应屏幕大小。我这一次使用DialogFragment做一个自动适应屏幕大小的例子,就是当屏幕不是平板那么大时,通过对话框显示Fragment,当屏幕是平板的时候,插入当前的activity显示。
这个实现主要通过创建几个对应不同大小的bools.xml文件,然后使用getResources().getBoolean(R.bool.large_layout) 来实现判断当前屏幕的大小。
使用例子如下:
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void showLoginDialog(View view)
{
FragmentManager fragmentManager = getFragmentManager();
EditNameDialogFragment newFragment = new EditNameDialogFragment();
boolean mIsLargeLayout = getResources().getBoolean(R.bool.large_layout) ;
Log.e("TAG", mIsLargeLayout + "");
if (mIsLargeLayout )
{
// The device is using a large layout, so show the fragment as a
// dialog
newFragment.show(fragmentManager, "dialog");
} else
{
// The device is smaller, so show the fragment fullscreen
FragmentTransaction transaction = fragmentManager
.beginTransaction();
// For a little polish, specify a transition animation
transaction
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
// To make it fullscreen, use the 'content' root view as the
// container
// for the fragment, which is always the root view for the activity
transaction.replace(R.id.id_ly, newFragment)
.commit();
}
}
}
public class EditNameDialogFragment extends DialogFragment
{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
if (getResources().getBoolean(R.bool.large_layout))
{
getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
}
View view = inflater.inflate(R.layout.fragment_edit_name, container,
false);
return view;
}
}
activity_main
fragment_edit_name
再见