码迷,mamicode.com
首页 > 其他好文 > 详细

Fragment的使用(二)

时间:2016-01-02 00:58:49      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:

动态添加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);
}
}

?

横向效果:

?

纵向效果:

?

?

Fragment的使用(二)

标签:

原文地址:http://www.cnblogs.com/deli990/p/5094017.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!