3月3日,Android发布了《Fragment For All》,标明Android为兼容各个低版本(最低1.6)做出了实质性的行动。 Fragment API类似iOS的Split View。另外,看过Fragment API以后,觉得应该也可以实现iOS的Popover。split view可见这里。popover可见简单的popover。 在Android 2.3.2上测试了Fragment的简单使用。效果如下: 模拟了split view的使用。 代码实现是非常简单的。但是android的文档没有跟上,造成上手时容易出现各种问题。可见发布还是很仓促的。 首先,需要通过Adnroid SDK update,更新Android兼容包。 然后,将Android SDK下面目录的文件: - extras/android/compatibility/v4/android-support-v4.jar
复制代码 复制到Eclipse ADT项目中,然后再设置到classpath中:再然后,就要开始写代码了。这时需要注意,Android官方文档是写给3.0的。直接引用将报错,比如ClassNotFoundException等。我尝试成功的方式是,通过编程来实现布局。(直接用fragment标签做布局会报错,可能是因为编译的时候不能加载android-support-v4包,或者是因为包名问题。)首先要注意,实现的Activity必须是继承:FragmentActivity。而3.0不需要,因为3.0将比如getFragmentManager()方法已经加入到Activity中了。而3.0以前版本要通过继承FragmentActivity获得类似功能。- public class FragmentDemoActivity extends FragmentActivity {
复制代码 编写主布局文件:- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="horizontal" android:layout_width="fill_parent"
- android:layout_height="fill_parent" android:id="@+id/rootView">
- <LinearLayout android:id="@+id/leftView"
- android:orientation="vertical" android:layout_width="0dp"
- android:layout_weight="1" android:layout_height="fill_parent"
- android:background="#c0c0c0c0"/>
- <LinearLayout android:id="@+id/rightView"
- android:orientation="vertical" android:layout_width="0dp"
- android:layout_weight="2" android:layout_height="fill_parent" />
- </LinearLayout>
复制代码 这样写是变通的做法,因为不能按照官方示例直接用fragment标签。编写左侧视图的布局:- <?xml version="1.0" encoding="utf-8"?>
- <TextView xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent" android:layout_height="wrap_content"
- android:text="demo left fragment" />
复制代码 右侧类似,也是TextView。编写Fragment实现类。比如左侧的:- package com.easymorse.demos;
- import android.os.Bundle;
- import android.support.v4.app.Fragment;
- import android.view.LayoutInflater;
- import android.view.View;
- import android.view.ViewGroup;
- public class DemoLeftFragment extends Fragment {
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- return inflater.inflate(R.layout.demo_left_fragment, container,false);
- }
- }
复制代码 在onCreateView方法中加入了上面的左侧视图。右侧类似。在Activity类中将两个Fragment集成起来:- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- FragmentManager fragmentManager=getSupportFragmentManager();
- FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
- DemoLeftFragment leftFragment=new DemoLeftFragment();
- DemoRightFramgment rightFramgment=new DemoRightFramgment();
- fragmentTransaction.add(R.id.leftView, leftFragment);
- fragmentTransaction.add(R.id.rightView, rightFramgment);
- fragmentTransaction.commit();
- }
复制代码 以上源代码见:目前代码还有bug,主要是需要对fragment生命周期学习了解。因为代码在锁屏解锁后,会出现类似:
|