您的位置:首页 > 移动开发 > Android开发

Android Fragment的三种应用方式

2016-04-29 10:57 531 查看
应用方式一:动态的使用Fragment

首先是,MainActivity的布局文件activity_main.xml,该文件布局文件上面的顶部是一个TitleFragment,是一个静态声明的Fragment。

中间也是一个Fragment,但是这个Fragment是动态使用的。

最下面是四个按钮。用include标签包含外部的布局文件进来的。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<fragment
android:id="@+id/id_fragment_title"
android:name="com.example.dynamicfragment.TitleFragment"
android:layout_width="fill_parent"
android:layout_height="45dp" />

<include
android:id="@+id/id_ly_bottombar"
android:layout_width="fill_parent"
android:layout_height="55dp"
android:layout_alignParentBottom="true"
layout="@layout/bottombar" />

<FrameLayout
android:id="@+id/id_content"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="@id/id_ly_bottombar"
android:layout_below="@id/id_fragment_title" />

</RelativeLayout>


然后是,MainActivity.java文件。也是我们这个demo当中最重要的代码文件,首先是将上面的布局文件通过setContentView()加载进来.然后是通过setDefaultFragment();将默认的ContentFragment动态的加载进来。接下来就是通过我们在最下面防止的四个按钮可以随意的动态切换Fragment。

public class MainActivity extends ActionBarActivity implements OnClickListener {
private ImageButton mTabWeixin;
private ImageButton mTabFriend;
private ImageButton mTabDiscover;
private ImageButton mTabMe;

private ContentFragment mWeiXinFragment;
private FriendFragment mFriendFragment;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);

initView();
}

public void initView() {
// 初始化控件和声明事件
mTabWeixin = (ImageButton) findViewById(R.id.weixin);
mTabFriend = (ImageButton) findViewById(R.id.friend);
mTabWeixin.setOnClickListener(this);
mTabFriend.setOnClickListener(this);

// 设置默认的Fragment
setDefaultFragment();
}

@SuppressLint("NewApi")
private void setDefaultFragment() {
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();

mWeiXinFragment = new ContentFragment();
transaction.replace(R.id.id_content, mWeiXinFragment);
transaction.commit();
}

@SuppressLint("NewApi")
@Override
public void onClick(View v) {
FragmentManager fm = getFragmentManager();
// 开启Fragment事务
FragmentTransaction transaction = fm.beginTransaction();
switch (v.getId()) {
case R.id.weixin:
if (mWeiXinFragment == null) {
mWeiXinFragment = new ContentFragment();
}
// 使用当前Fragment的布局替代id_content的控件
transaction.replace(R.id.id_content, mWeiXinFragment);
break;
case R.id.friend:
if (mFriendFragment == null) {
mFriendFragment = new FriendFragment();
}
transaction.replace(R.id.id_content, mFriendFragment);
break;
}
// transaction.addToBackStack();
// 事务提交
transaction.commit();
}
}


从上面的代码,我们可以看出,我们可以使用FragmentManager对Fragment进行动态的加载,这里使用的replace方法

注:如果使用android3.0一下的版本,需要引入v4的包,然后Activity继承FragmentActivity,然后通过getSupportFragmentManager()获得FragmentManager对象,不过还是建议把Menifest文件的uses-sdk的minSdkVersion和targetSdkVersion都改为11以上,这样就不必引入v4的包了。

代码的中间有俩个动态加载进来的Fragment,这个和静态使用ragment的声明方式是一样的,写一个继承Fragment的类,然后设置相应的布局,由于时间的关系,我这里只写了俩个Fragment,现在把这俩个的代码页贴出来:

第一个Fragment和他相应的布局文件:

public class ContentFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment_content, container, false);
}
}


<?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:orientation="vertical" >

<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:text="weixin"
android:textSize="20sp"
android:textStyle="bold" />

</LinearLayout>


应用方式二:静态使用

这是使用Fragment最简单的一种方式,把Fragment当成普通的控件,直接写在Activity的布局文件中,用布局文件调用Fragment。

步骤:

1、继承Fragment,重写onCreateView决定Fragment布局。

2、在Activity中声明此Fragment,就当和普通的View一样。

下面展示一个例子(我使用俩个Fragment作为Activity的布局,一个Fragment用于标题布局,一个Fragment用于内容布局)。

TitleFragment的布局文件,在这里我们可以看出,我们可以每个Fragment当中进行单独的布局:

下面就是主Activity以及他的布局文件

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
}
}


activity_main.xml布局文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.staticfragment.MainActivity" >

<fragment
android:name="com.example.staticfragment.TitleFragment"
android:id="@+id/title"
android:layout_height="45dp"
android:layout_width="match_parent"/>
<fragment
android:layout_below="@id/title"
android:name="com.example.staticfragment.ContentFragment"
android:id="@+id/content"
android:layout_height="fill_parent"
android:layout_width="fill_parent"/>

</RelativeLayout>


TitleFragment.java文件,在这里我们能够看到,可以在各个Fragment当中进行独立的初始化空间并且处理按钮之类的事件,减轻了Activity的负担,我们在Activity中就没有必要写一大推初始化控件和事件响应的代码了,这样就使我们的代码看上去更加的简洁了,可读性大大提高了。

如果引用:

public class TitleFragment extends Fragment {

private ImageButton mButton;
@SuppressLint("NewApi")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.title_fragment, container, false);
mButton = (ImageButton)view.findViewById(R.id.id_title_left_btn);
mButton.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
Toast.makeText(getActivity(),   "i am an ImageButton in TitleFragment ! ",   Toast.LENGTH_SHORT).show();
}
});
return view;
}

}


title_fragment.xml布局文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="45dp"
android:background="@drawable/title_bar" >

<ImageButton
android:id="@+id/id_title_left_btn"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_centerVertical="true"
android:background="@drawable/showleft_selector" />

<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:text="我不是微信"
android:textColor="#fff"
android:textSize="20sp"
android:textStyle="bold" />

</RelativeLayout>


同理还有ContentFragment的布局文件content_fragment.xml

<?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:orientation="vertical" >

<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:text="使用Fragment做主面板"
android:textSize="20sp"
android:textStyle="bold" />

</LinearLayout>


同理还有ContentFragment.java文件

public class ContentFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.content_fragment, container,false);
}

}


应用三:使用ViewPager

把fragment组装成一个数组,使用setAdapter方法把fragment添加到viewpager

详细代码如:

首先定义标题,根据标题的长度创建对应的fragment

public class ViewPagerActivity extends FragmentActivity {
private String[] mTitles = new String[] { "简介", "评价", "相关" };
//创建viewpager
private ViewPager mViewPager;
//定义数据数组
private TabFragment[] mDatas = new TabFragment[mTitles.length];
//定义标题控件
List<ColorChangeView> mTabs = new ArrayList<ColorChangeView>();

private FragmentPagerAdapter mAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_viewpager);
initViews();
initDatas();
initEvenvts();
}

private void initViews() {
mViewPager = (ViewPager) findViewById(R.id.id_viewpager);
}

private void initDatas() {
for (int i = 0; i < mTitles.length; i++) {
mDatas[i] = TabFragment.newInstance(mTitles[i]);
}

mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
@Override
public int getCount() {
return mTitles.length;
}

@Override
public Fragment getItem(int position) {
return mDatas[position];
}
};

mViewPager.setAdapter(mAdapter);
mViewPager.setCurrentItem(0);
}

private void initEvenvts() {
mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int position) {

}

@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (positionOffset > 0) {
ColorChangeView left = mTabs.get(position);
left.setDirection(ColorChangeView.DIRECTION_LEFT);
left.setProgress(1-positionOffset);
ColorChangeView right = mTabs.get(position+1);
right.setDirection(ColorChangeView.DIRECTION_RIGHT);
right.setProgress(positionOffset);
}

}

@Override
public void onPageScrollStateChanged(int state) {

}
});

}
}


对应的布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:koo="http://schemas.android.com/apk/res/com.android.view"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal" >

<com.android.view.colortextview.ColorChangeView
android:id="@+id/id_tab_01"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
koo:progress="1"
koo:text="简介"
koo:text_change_color="#ffff0000"
koo:text_origin_color="#ff000000"
koo:text_size="18sp" />

<com.android.view.colortextview.ColorChangeView
android:id="@+id/id_tab_02"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
koo:text="评价"
koo:text_change_color="#ffff0000"
koo:text_origin_color="#ff000000"
koo:text_size="18sp" />

<com.android.view.colortextview.ColorChangeView
android:id="@+id/id_tab_03"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
koo:text="相关"
koo:text_change_color="#ffff0000"
koo:text_origin_color="#ff000000"
koo:text_size="18sp" />

</LinearLayout>

<android.support.v4.view.ViewPager
android:id="@+id/id_viewpager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" >
</android.support.v4.view.ViewPager>

</LinearLayout>


对应的fragment

public class TabFragment extends Fragment {
public static final String TITLE = "title";
private String mTitle = "Defaut Value";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mTitle = getArguments().getString(TITLE);
}
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
TextView tv = new TextView(getActivity());
tv.setTextSize(60);
Random r = new Random();
tv.setBackgroundColor(Color.argb(r.nextInt(120), r.nextInt(255), r.nextInt(255), r.nextInt(255)));
tv.setText(mTitle);
tv.setGravity(Gravity.CENTER);
return tv;
}

public static TabFragment newInstance(String title) {
TabFragment tabFragment = new TabFragment();
Bundle bundle = new Bundle();
bundle.putString(TITLE, title);
//保存标题信息
tabFragment.setArguments(bundle);
return tabFragment;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: