如何獲取螢幕的狀態以及橫屏與豎屏自動切換
阿新 • • 發佈:2019-02-08
demo1:獲取螢幕的狀態 ,橫屏與豎屏自動切換fragment
publicclassMainActivityextendsActivity{
@Override
protectedvoid onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//獲取螢幕的寬度和高度 適配不同的fragment
DisplayMetrics outMetrics=newDisplayMetrics();
getWindowManager
int width=outMetrics.widthPixels;
int height=outMetrics.heightPixels;
RelativeLayout layout=(RelativeLayout)findViewById(R.id.layoutId);
//要藉助此物件管理fragment物件
FragmentManager fm= getFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
//使用不同的fragment
if(
ft.replace(R.id.layoutId,newFragment01(),"tag");
}else{
ft.replace(R.id.layoutId,newFragment02(),"tag");
}
//可選:將fragment新增到回退棧
//ft.addToBackStack(null);
ft.commit();
}
@Override
protectedvoid onResume(){
super.onResume();
//根據tag找到對應的fragment
Fragment f=getFragmentManager().findFragmentByTag
Log.i("TAG","f="+f);
}
}
demo2:Tab+fragment 實現螢幕旋轉儲存資料
publicclassMainActivityextendsActivity{
ActionBar bar;
@Override
protectedvoid onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bar=getActionBar();
bar.setDisplayShowHomeEnabled(false);
bar.setDisplayShowTitleEnabled(false);
//設定為tab導航
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//新增tab
bar.addTab(bar.newTab().setText("tab01").setTabListener(
newMyTabListener(this,Fragment01.class.getName(),"A")));
bar.addTab(bar.newTab().setText("tab02").setTabListener(
newMyTabListener(this,Fragment02.class.getName(),"B")));
}
@Override
protectedvoid onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
if(savedInstanceState!=null){
int pos=savedInstanceState.getInt("posKey");
bar.setSelectedNavigationItem(pos);
}
}
privateclassMyTabListenerimplementsTabListener{
privateContext context;
privateString className;
privateFragment frg;
privateString tag;
publicMyTabListener(Context context,String className,String tag){
this.context=context;
this.className=className;
this.tag=tag;
//檢測在當前activity是否已經有存在的fragment
Fragment frg=getFragmentManager().findFragmentByTag(tag);
if(frg!=null&&!frg.isDetached()){
FragmentTransaction beginTransaction = getFragmentManager().beginTransaction();
beginTransaction.detach(frg);
beginTransaction.commit();
}
}
@Override
publicvoid onTabSelected(Tab tab,FragmentTransaction ft){
if(frg==null){
frg=Fragment.instantiate(context, className);
ft.add(R.id.layout,frg,tag);
}else{
ft.attach(frg);
}
}
//沒有選中的那個在旋轉需要解除關聯
@Override
publicvoid onTabUnselected(Tab tab,FragmentTransaction ft){
if(frg!=null){
ft.detach(frg);
}
}
@Override
publicvoid onTabReselected(Tab tab,FragmentTransaction ft){
}
}
@Override
protectedvoid onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
int pos=bar.getSelectedTab().getPosition();
outState.putInt("posKey", pos);
}
}