Fragment

关于Fragment

Fragment是什么

实现两个activity动态页面的切换
1.解决局部刷新
2.解决屏幕适配问题
由来:3.0版本之后出现,为了解决屏幕碎片化
优点:解决了activity的切换不流畅,布局切换轻量化

.静态加载

1.new–>Fragment–>Fragment(Blank)
2.去掉两个√
3.Fragment的·布局:

<FrameLayout 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.xiaozhen.mynewapplication.fragment.HelloFragment">

<!-- TODO: Update blank fragment layout -->
<TextView
android:background="#5ff0"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="hello" />

</FrameLayout>

4.然后再在activity的布局文件中添加<fragment>标签

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

tools:context="com.example.xiaozhen.mynewapplication.MainActivity">
<fragment
android:name="com.example.xiaozhen.mynewapplication.fragment.HelloFragment"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="@+id/fragment">
</fragment>
<fragment
android:layout_weight="1"
android:name="com.example.xiaozhen.mynewapplication.fragment.listFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="@+id/fragment1">
</fragment>
</LinearLayout>

.动态加载

步骤:(1):新建类继承fragment
(2):重写onCreat()方法
(3):使用LayoutInflate方法绑定布局和控件
(4)使用FragmentManage()FragmentTransation()

1.在activity布局文件中添加<FrameLayout>一定要给id
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.xiaozhen.mynewapplication.FragmentActivity">

<LinearLayout
android:orientation="vertical"
android:layout_width="100dp"
android:layout_height="match_parent">
<Button
android:id="@+id/btn1"
android:text="页面一"
android:layout_width="100dp"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btn2"
android:text="页面二"
android:layout_width="100dp"
android:layout_height="wrap_content" />
</LinearLayout>
<FrameLayout
android:id="@+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>

2.初始化下面两个控件

private FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;

fragmentManager=getFragmentManager();
fragmentTransaction=fragmentManager.beginTransaction();

3.添加单击事件,同时还要加载之前的两个fragment:ListFragment和HelloFragment(默认都是导的v4包,这里实现动态加载需要将V4包替换成app包,否则会一直报错)
判断是否两个fragment为空,若是就重新初始化两个fragment
用 fragmentTransaction.replace()方法把动态的布局加进去
里面有两个参数1.把动态布局加进去,两个fragment(这里如果创建的fragment导包是V4包,则会报错)

代码如下:
package com.example.xiaozhen.mynewapplication;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;

import com.example.xiaozhen.mynewapplication.fragment.DongFragment;
import com.example.xiaozhen.mynewapplication.fragment.LianxiRFragment;
import com.example.xiaozhen.mynewapplication.fragment.WXFragment;

public class YemianActivity extends AppCompatActivity implements View.OnClickListener{
private Button btn_wx,btn_lxr,btn_dong;
private FrameLayout frameLayout;
private WXFragment wxfragment;
private LianxiRFragment lianxirfragmet;
private DongFragment dongfragment;
private FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yemian);
init();
fragmentManager=getFragmentManager();



}

private void init() {
btn_wx= (Button) findViewById(R.id.btn_wx);
btn_dong= (Button) findViewById(R.id.btn_dong);
btn_lxr= (Button) findViewById(R.id.btn_lxr);
btn_wx.setOnClickListener(this);
btn_lxr.setOnClickListener(this);
btn_dong.setOnClickListener(this);
}

@Override
public void onClick(View v) {
fragmentTransaction=fragmentManager.beginTransaction();
switch (v.getId()){
case R.id.btn_wx:
if (wxfragment==null){
wxfragment=new WXFragment();
}
fragmentTransaction.replace(R.id.frag,wxfragment);
break;
case R.id.btn_dong:
if (dongfragment==null){
dongfragment=new DongFragment();
}
fragmentTransaction.replace(R.id.frag,dongfragment);
break;
case R.id.btn_lxr:
if (lianxirfragmet==null){
lianxirfragmet=new LianxiRFragment();
}
fragmentTransaction.replace(R.id.frag,lianxirfragmet);
break;
default:
break;


}
fragmentTransaction.commit();   //
}
}

.ViewPage+Fragment实现页卡滑动

需要用到fragment和adapter
首先创建三个fragment
代码如下:

<FrameLayout 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.xiaozhen.mynewapplication.fragment.ChatFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:background="#ff0"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="聊天" />


</FrameLayout>

这里只举例一个fragment,其余两个参考上面

接着创建适配器FragmentAdapter继承FragmentPagerAdapter实现其未实现的方法,需要用数组将需要加载的fragment放在数组里

package com.example.xiaozhen.mynewapplication.adapter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import java.util.List;

/**
 * Created by xiaozhen on 2018/6/5.
 */

public class MyAdapter extends FragmentPagerAdapter {
    private List<Fragment> fragmentList;
    public MyAdapter(FragmentManager fm,List<Fragment> fragmentList) {
        super(fm);
      this.fragmentList=fragmentList;

    }

    @Override
    public Fragment getItem(int position) {
        return fragmentList.get(position);
    }

    @Override
    public int getCount() {
        return fragmentList.size();
    }
}

接着在activity中首先初始化绑定所用到的控件这里用了一个方法init()把需要绑定id的控件都放在了一起,接着初始化三个需要加载的fragment直接用new初始化即可;把fragment加到fragmentlist中,调用.add()方法添加进去;初始化适配器,里面有两个参数,第一个是getSupportFragmentManager(),第二个是数组
;调用 viewpage.setAdapter(adapter);把适配器添加进去

要实现滑动变颜色应该用 viewpage.setOnPageChangeListener(new ViewPager.OnPageChangeListener() 这个方法

其中有三个方法
public void onPageScrolled():实现回滚
public void onPageSelected(int position) :实现滑动页卡切换的操作
public void onPageScrollStateChanged(int state) {
这里我们只需要在 public void onPageSelected(int position)方法中做操作

接着添加单击事件,实现页卡的左右滑动用 viewpage.setCurrentItem(0)这个方法

最后添加监听事件

package com.example.xiaozhen.mynewapplication;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

import com.example.xiaozhen.mynewapplication.adapter.MyAdapter;
import com.example.xiaozhen.mynewapplication.fragment.ChatFragment;
import com.example.xiaozhen.mynewapplication.fragment.ContenctFragment;
import com.example.xiaozhen.mynewapplication.fragment.FriendFragment;

import java.util.ArrayList;
import java.util.List;

public class Example1Activity extends AppCompatActivity implements View.OnClickListener {
    private TextView tv_wx, tv_lxr, tv_dong;
    private View v1, v2, v3;
    private ChatFragment chatFragment;
    private FriendFragment friendfragment;
    private ContenctFragment contenctFragment;
    private List<Fragment> listFragment = new ArrayList<>();

    private ViewPager viewpage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_example1);
        init();
        chatFragment = new ChatFragment();
        contenctFragment = new ContenctFragment();
        friendfragment = new FriendFragment();

        listFragment.add(chatFragment);
        listFragment.add(friendfragment);
        listFragment.add(contenctFragment);

        MyAdapter adapter = new MyAdapter(getSupportFragmentManager(), listFragment);
        viewpage.setAdapter(adapter);
        tv_wx.setOnClickListener(this);
        tv_lxr.setOnClickListener(this);
        tv_dong.setOnClickListener(this);

        viewpage.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                v1.setBackgroundColor(Color.GRAY);
                v2.setBackgroundColor(Color.GRAY);
                v3.setBackgroundColor(Color.GRAY);
                switch (position) {
                    case 0:
                        v1.setBackgroundColor(Color.BLUE);
                        break;
                    case 1:
                        v2.setBackgroundColor(Color.BLUE);
                        break;
                    case 2:
                        v3.setBackgroundColor(Color.BLUE);
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void init() {

        tv_wx = (TextView) findViewById(R.id.tv_wx);
        tv_lxr = (TextView) findViewById(R.id.tv_lxr);
        tv_dong = (TextView) findViewById(R.id.tv_dong);
        viewpage = (ViewPager) findViewById(R.id.viewpage);
        v1 = findViewById(R.id.v1);
        v2 = findViewById(R.id.v2);
        v3 = findViewById(R.id.v3);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_wx:
                viewpage.setCurrentItem(0);
                break;
            case R.id.tv_lxr:
                viewpage.setCurrentItem(1);
                break;
            case R.id.tv_dong:
                viewpage.setCurrentItem(2);
                break;
            default:
                break;
        }
    }
}

三:生命周期

**onAttach();
onCreate();
onCreatView();
onStart();
onResume();
OnPause();
onStop();
onDestoryView();
onDestory();
onDetach();**
代码:

package com.example.xiaozhen.mynewapplication.fragment;


import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.xiaozhen.mynewapplication.R;

/**
 * A simple {@link Fragment} subclass.
 */
public class FriendFragment extends Fragment {
private String TAG="FriendFragment";

    public FriendFragment() {
        // Required empty public constructor
    }

    public void onAttach(Context context) {
        super.onAttach(context);
        Log.e(TAG,"onAttach******************");
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e(TAG,"onCreate******************");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_friend, container, false);
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.e(TAG,"onStart******************");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.e(TAG,"onResume******************");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.e(TAG,"onPause******************");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.e(TAG,"onCreate******************");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.e(TAG,"onDestroyView******************");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e(TAG,"onDestroy******************");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.e(TAG,"onDetach******************");
    }

}

这里写图片描述

ViewPage会预加载左右两个fragment
fragment从不可见到可见一定会执行 onStart(),onResume()
从可见到不可见执行的数据操作要放在onResume()

Fragment的传值

Fragment与activity之间的通信

1.从fragment向activity传递:

1.在fragment的
public View onCreateView()方法中
先创建view视图
View view=inflater.inflate(R.layout.fragment_friend, container, false);
然后通过 view.findViewById()绑定id
对button进行添加单击事件
创建activity对象,通过对象.方法的方式得到activity中的传值方法

public View onCreateView (LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view=inflater.inflate(R.layout.fragment_friend, container, false);
button_title= (Button) view.findViewById(R.id.btn_title);
button_title.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
YemianActivity yemianActivity= (YemianActivity) getActivity();
yemianActivity.test("我是朋友圈fragment");
}
});
return view;
}

2.activity中的Test方法:

public void test(String title) {
tv_title.setText(title);
}

activity向fragment进行传值:

1.首先在activity中添加Bundle
对Bundle进行初始化,
把值传进去用 bundle.putString(“name”,”诸彦修”);方法
将需要的fragment用.setArguments(bundle);
将bundle加进去
activity:

 friendfragment=new FriendFragment();
        chatFragment=new ChatFragment();
        contenctFragment=new ContenctFragment();

        **Bundle bundle=new Bundle();
        bundle.putString("name","诸彦修");
       friendfragment.setArguments(bundle);**

        listFragment.add(friendfragment);
        listFragment.add(chatFragment);
        listFragment.add(contenctFragment);


        MyAdapter adapter = new MyAdapter(getSupportFragmentManager(), listFragment);
        viewPager.setAdapter(adapter);

    }

friend Fragment:

 public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_friend, container, false);
        button_title = (Button) view.findViewById(R.id.buton_title);
        button_title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentczActivity fragmentczActivity = (FragmentczActivity) getActivity();
                fragmentczActivity.test("我是朋友圈fragment");

                ********Bundle bundle = getArguments();
                String name = bundle.getString("name");
                button_title.setText(name);***
            }
        });


        return view;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值