首页 > 其他分享 >Android Fragment的三种应用方式

Android Fragment的三种应用方式

时间:2023-02-14 10:33:27浏览次数:39  
标签:layout parent Fragment id public 三种 Android android


应用方式一:动态的使用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;
}
}

标签:layout,parent,Fragment,id,public,三种,Android,android
From: https://blog.51cto.com/u_12516227/6055880

相关文章

  • 三种不同的考核方式
    一、KPI:关键绩效指标KPI是关键绩效指标,用于根据某个单位在一段时间内的绩效来评估某个目标,例如公司、个人、计划、项目或特定任务。可能会有一些不寻常的案例和数值,但一般......
  • Android 之 环境搭建
    1.Gradlegradle跟maven一样是一个包管理工具,Android项目默认的包管理工具,这两天使用下来,感觉比maven更加简洁,其他暂时没啥赶脚。1.1配置Javagradle需要java8+1.2......
  • CSS 实现水平和垂直居中的三种方法
    绝对定位+负边距:使用绝对定位并设置左右负边距和上下负边距,就可以实现水平和垂直居中的效果。.center-element{position:absolute;top:50%;left:50%;......
  • AppsFlyer SDK 接入( Android )
    第1步:声明存储库在Project项目目录的build.gradle文件中,声明mavenCentral存储库://...repositories{mavenCentral()}///...第2步:添加依赖项在Application的build......
  • 2023-02-13 Android studio打包apk到手机上(模拟器也一样)运行时闪退
    环境:Rn项目apk,win10,android手机,as版本为4.2.2。======================================================================================================这是由chatG......
  • 2023-02-13 【Android studio内存不足】 Out of memory: Java heap space. Configure
    我的as版本:4.2.2测试环境:Android要修改as内存,需要修改两个地方:1、打开as,找到帮助==>更改内存设置==>最大堆大小,把2048修改成你想要的值,我是改成了8192,就是8g内存,接着重......
  • Solon2 开发之容器,五、Bean 扫描的三种方式
    1、启动时扫描packageorg.example.demo;publicclassDemoApp{publicstaticvoidmain(String[]args){////DemoApp.clas的作用,是提供一个......
  • Android_Handler
    [CallBack]JAVA回调函数简单讲解CallBackJava-回调函数 [Handler]Java中Handler的标准使用方式 Handler全解Handler源码分析-Java层 ......
  • Solon2 开发之容器,二、构建一个 Bean 的三种方式
    1、手动简单的构建://生成普通的BeanSolon.context().wrapAndPut(UserService.class,newUserServiceImpl());//生成带注解的Bean(比如:@Controller)Solon.context().be......
  • Java基础知识点(if语句的第二种和第三种)
    一:if语句的第二种格式1.格式:if(关系表达式){语句体1;​}else{语句体2;}2.执行流程:1.首先计算关系表达式的值。2.如果关系表达式的值为true,就执行语句体1.3.如果关系表达式的值......