在新版本的安卓中,系统提供了一个新的组件--fragment,使我们可以自己动态的修改界面.下面是跟老师学习的一个简单的示例代码:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//1.判断当前手机的朝向
int width = getWindowManager().getDefaultDisplay().getWidth();
int height = getWindowManager().getDefaultDisplay().getHeight();
Fragment1 fragment1 = new Fragment1();
Fragment2 fragment2 = new Fragment2();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
if (width>height) {
//水平方向
ft.replace(android.R.id.content, fragment1);
} else {
ft.replace(android.R.id.content, fragment2);
}
ft.commit();
}
}
xml 配置初始.在layout中创建两个fragment.一个红色,一个蓝色.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#0000ff"
android:orientation="vertical" >
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff0000"
android:orientation="vertical" >
</LinearLayout>
另外在src包内创建两个fragment.
package com.example.fragment;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment1 extends Fragment {
//当fragment被创建的时候调用的方法,返回当前fragment显示的内容
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment1, null);
}
}
fragment2 与1 类似,这里就不贴了.
测试后竖直屏幕显示红色,横屏显示蓝色.
源码下载地址:点击打开链接