Fragment

1、Fragment的出现解决屏幕大小适配问题比如小屏幕手机和大屏手机等。
使用Fragment 组件是需要使用帧布局的。 (FrameLayout 帧布局)android 3.0
应用时:
创建fragment类(继承app.fragment)要求最低api等级是11.;
类里面定义的方法是:(override 重写父类的方法 onCreateView)
根据里面的布局填充器。inflater(填充器);的inflate方法填充布局文件layout(可以是任意布局)。
将创建的fragment定义的view显示到 帧布局上。
步骤:
1,建一个Fragment类的对象;
2,创建FragmentManager管理器象。; getFragmentManager
3,开启事务对象。 fm.beginTransaction(); FragmentTransaction 事务对象
4,将创建的fragment内容显示到帧布局上。 ft.replace(containerViewId, fragment) containerViewId指的是盛放View对象的资源文件也就是帧布局的资源id. fragment也就是 创建的Fragment对象。
5。事务提交。 ft.commit(); 事务的提交。、
demo:

public void click2(View v) {
        Fragment2 fm2 = new Fragment2();
        // 创建Fragment管理器;
        FragmentManager fm = getFragmentManager();
        // 开启事务
        FragmentTransaction ft = fm.beginTransaction();
        // 将Fragment的内容显示再帧布局上。
        ft.replace(R.id.fl, fm2);
        ft.commit();   //事务的提交一定要记住。

    }

定义layout的两套布局文件:

<LinearLayout 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"
    android:orientation="horizontal" >

    <FrameLayout
        android:id="@+id/fl"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" >  //利用权重将布局分开,不至于将左边的组件从屏幕中挤出。
    </FrameLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="click1"
            android:text="fragment1" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="click2"
            android:text="fragment2" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="click3"
            android:text="fragment3" />
    </LinearLayout>

</LinearLayout>

这个是帧布局在右边,其他组件在左边:

<LinearLayout 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"
    android:orientation="horizontal" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="click1"
            android:text="fragment1" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="click2"
            android:text="fragment2" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="click3"
            android:text="fragment3" />
    </LinearLayout>

    <FrameLayout
        android:id="@+id/fl"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </FrameLayout>

</LinearLayout>

向下兼容:
将android 自带的Fragment的api改成支持类库support中的api.
getFragmentManager()的api所属于activity.
所以继承的actiity要改成安卓支持jar包中的FragmentActiivty.
注意一下获取管理器的时候,得改成getSupportFragmentManager();
这样Fragment就能兼容3.0一下的版本了。
support-v4
demo:

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;

public class MainActivity extends FragmentActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
            Fragment3 fm3 = new Fragment3();
            FragmentManager fm = getSupportFragmentManager();//这个需要自己注意。改下,
            FragmentTransaction ft = fm.beginTransaction();
            ft.replace(R.id.fl, fm3);
            ft.commit();

    }

Fragment 和activity之间数据的传递:
activity传到Fragment时: activity建立点击事件:得到EditText对象,然后获得输入的数据;
由于Fragment在建的时候直接建立的有对象(在接收端,Fragment中建立一个组件,Textview用来显示得到的数据,在Fragment类中建立显示数据的方法,该方法中需要传递一个数据)
在点击事件中可以直接利用Fragment对象获得设置显示的方法,将得到的输入数据传递到Fragment端。
demo:
建立显示端Fragment对象的显示方法;

package com.zh.senddata;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class Fragment3 extends Fragment {


    private TextView tv_display;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View v = inflater.inflate(R.layout.fragment03, null);
         tv_display = (TextView) v.findViewById(R.id.tv_display);

        return v;

    }
       public void setText(String text){
            tv_display.setText(text);

       }
}

在activity端,点击事件中可以直接调用Fragment对象的显示方法,以实现数据的传递;
demo:

 public void click4(View v){
        EditText et_main = (EditText) findViewById(R.id.et_main);  
         String text =  et_main.getText().toString();
        //传递数据‘
         fm3.setText(text);

    }

从Fragment端往activity端进行数据传递的方法:
在Fragment 对象中创建 EditText组件,进行写入数据,通过findViewById得到其对象,然后再经过getText()方法得到输入的数据,在Fragment 端发送数据的关键是在Fragment中能拿到activity对象,方法是getAcitivity;为了调用MainActivity中的方法需要将getActivity强转成MainActivity;
在这里需要注意设置点击事件就不能用Button自带的onclick的属性了,设置点击侦听。
这是Fragment 发送端:

package com.zh.senddata;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.Button;
import android.widget.EditText;

public class Fragment2 extends Fragment {
    private EditText et_send2;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View v = inflater.inflate(R.layout.fragment02, null);
        Button bt = (Button) v.findViewById(R.id.bt);
        et_send2 = (EditText) v.findViewById(R.id.et_send2);
        bt.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                String text = et_send2.getText().toString();
                //获得并强转成MainActivity对象,设置传输数据
                ((MainActivity)getActivity()).setText(text);

            }
        });

        return v;

    }
}

activity端设置显示的组件及方法:

  public void setText(String text){
        EditText  et=(EditText) findViewById(R.id.et_main); //注意这个组件的id定义时不能和Fragment端的相同,     
        et.setText(text);                 如果相同,由于该方法在Fragment端调用,所以在查询View时会在Fragment中
                                            查找,就会出现数据传递不出去实际上数值传递了自己本身。 
    }

解决办法有两个:一是。设置的资源id不一样就可以了,第二种是将EditText得到的对象设置为全局变量,那样就不会再被赋值了。

public class MainActivity extends Activity {

    private Fragment3 fm3;
    private EditText et;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et = (EditText) findViewById(R.id.et);  
            fm3 = new Fragment3();
  public void setText(String text){

        et.setText(text);      //这样再Fragment中调用该方法时就不会出现上述问题。

    }

Fragment的生命周期方法和activity的基本相同,Fragment创建,开启,Resume,stop,destory。Fragment的生命周期通常绑定activity的生命周期。
2,一个Fragment创建,另一个Fragment就有先Stop,Destory/.然后再被oncreate,onstart,onresume.

### 定义 Fragment 意思是“碎片、片段”,表示 Activity 中的行为或用户界面部分,是 Activity 的模块化组成部分,可将多个片段组合在一个 Activity 中来构建多窗格 UI,也能在多个 Activity 中重复使用某个片段。它具有自己的生命周期,能接收自己的输入事件,可在 Activity 运行时添加或移除,可当作“子 Activity”在不同 Activity 中复用。Fragment 作为 Activity 界面的一部分必须依附于 Activity,与 Activity 一样拥有自己的生命周期,还能处理用户的交互动作。同一个 Activity 可以有一个或多个 Fragment 作为界面内容,可动态添加、删除 Fragment,灵活控制 UI 内容,也可用于解决部分屏幕适配问题 [^2][^4][^5]。 ### 使用方法 #### 静态使用 将 Fragment 当成普通的 View 一样声明在 Activity 的布局中,事件处理交给 Fragment。步骤如下: 1. 在 Activity 布局中添加 fragment 控件,用于加载想要显现的视图。 2. 创建 Fragment 类继承 Fragment,重写其中的 onCreateView(),使用 inflate 加载 Fragment 布局并返回视图 [^2]。 #### 动态使用 动态加载时,因有许多完成特定功能的 Fragment,所以需要对其进行管理,这时用到 FragmentManage 类。对 Fragment 进行添加、移除、替换等操作需通过 Fragment 事务处理,用到 FragmentTransaction 类。步骤如下: 通过 FragmentManager.beginTransaction() 开始一个事务,可在事务中对 Fragment 进行操作,如添加 add()、移除 remove()、替换 replace() 等,最后提交事务 commit(),还有 addToBackStack()、attach() 等操作。注意,Fragment 通过 ID 或者 Tag 作为标识,对 Fragment 操作后一定要提交,即调用 commit() [^2]。 ### 应用场景 Fragment 的目的是为了解决在不同的显示屏上动态和灵活的 UI 设计。可用于构建多窗格 UI,在同一个 Activity 中组合多个片段;可动态添加、删除 Fragment,灵活控制 UI 内容;还能用来解决部分屏幕适配问题 [^2][^4]。 ### 代码示例 以下是自定义 MyFragmentPagerAdapter 继承自 FragmentPagerAdapter 的示例代码: ```java import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentPagerAdapter; public class MyFragmentPagerAdapter extends FragmentPagerAdapter { public MyFragmentPagerAdapter(FragmentManager fm) { super(fm); } // 滑动的过程中呈现的Fragment的确定 @Override public Fragment getItem(int arg0) { Fragment fragment = null; switch (arg0) { case 0: fragment = new FragmnetFirst(); break; case 1: fragment = new FragmentSecond(); break; case 2: fragment = new FragmentThird(); break; } return fragment; } // 滑动的过程中可以呈现Fragment的个数 @Override public int getCount() { return 3; } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值