标签:
动态添加Fragment
将MainActivity的布局文件中的两个Fragment的代码注释掉。在MainActivity的java文件中添加如下代码:
package com.cm.myfragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//动态添加Fragment
dynamicAddFragment();
}
private void dynamicAddFragment(){
FragmentManager manager=getFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
WindowManager wManager=getWindowManager();
Display display=wManager.getDefaultDisplay();
if(display.getWidth()>display.getHeight()){
//当前手机处于横屏模式landscape
Fragment1 f1=new Fragment1();
transaction.replace(android.R.id.content,f1);
}else{
//当前手机处于纵向模式portrait
Fragment2 f2=new Fragment2();
transaction.replace(android.R.id.content,f2);
}
transaction.commit();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
?
横向效果:
?
纵向效果:
?
?
标签:
原文地址:http://www.cnblogs.com/deli990/p/5094017.html