Fragment

来源:互联网 发布:java脱产班 编辑:程序博客网 时间:2024/05/21 17:27

一、Fragment简单说明

  • fragment有自己的生命周期
  • 管理用户界面的Fragment又称为UI fragment
  • 采用fragment来管理应用UI可绕开activity使用的规则的限制
  • fragment依赖于activity
  • fragment可通过getActivity()来获取Activity,Activity可通过FragmentManager的findFragmentById()或findFragmentByTag()来获取fragment

二、切换fragment、fragment传递数据给activity、activity传递数据给fragment

(1)java文件

1、FragmentActivity.java

package com.lcfu1.all.Fragment;import android.app.Fragment;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;import com.lcfu1.all.R;public class FragmentActivity extends AppCompatActivity {    private TextView mTextView;    private Button mChange;    private Button mTransmit;    private Fragment mAFragment;    private Fragment mBFragment;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_fragment);        mTextView=(TextView)findViewById(R.id.textview);        //显示AFragment        mAFragment=new AFragment();        getFragmentManager().beginTransaction().replace(R.id.fragment,mAFragment).commitAllowingStateLoss();        //切换到BFragment        mChange=(Button)findViewById(R.id.change);        mChange.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                mBFragment=new BFragment();                //addToBackStack(null)添加到回退栈中                getFragmentManager().beginTransaction().replace(R.id.fragment,mBFragment).addToBackStack(null).commitAllowingStateLoss();            }        });        //在activity中把hello传给AFragment        mTransmit=(Button)findViewById(R.id.transmit);        mTransmit.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                mAFragment=AFragment.newInstance("hello");                getFragmentManager().beginTransaction().replace(R.id.fragment,mAFragment).commitAllowingStateLoss();            }        });    }    //接收AFragment传来的数据    public void setData(String textview){        mTextView.setText(textview);    }}

2、AFragment.java

package com.lcfu1.all.Fragment;import android.app.Fragment;import android.os.Bundle;import android.support.annotation.Nullable;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.Button;import android.widget.TextView;import com.lcfu1.all.R;/** * Created by cf on 2017/12/19. *///这里以android.app.Fragmen为超类public class AFragment extends Fragment {    private TextView mTextView;    private Button mCommit;    public static AFragment newInstance(String textview){        AFragment aFragment=new AFragment();        Bundle bundle=new Bundle();        bundle.putString("textview",textview);        aFragment.setArguments(bundle);        return aFragment;    }    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {        View view=inflater.inflate(R.layout.fragment_a,container,false);        return view;    }    @Override    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {        super.onViewCreated(view, savedInstanceState);        mTextView=(TextView)view.findViewById(R.id.textview);        //在AFragment中接收activity传来的数据        if(getArguments()!=null){            mTextView.setText(getArguments().getString("textview"));        }        //从AFragment中传递数据给activity        mCommit=(Button)view.findViewById(R.id.commit);        mCommit.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                ((FragmentActivity)getActivity()).setData("我是从AFragment传来的");            }        });    }}

3、BFragment.java

package com.lcfu1.all.Fragment;import android.app.Fragment;import android.os.Bundle;import android.support.annotation.Nullable;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import com.lcfu1.all.R;/** * Created by cf on 2017/12/19. *///这里以android.app.Fragmen为超类public class BFragment extends Fragment {    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {        View view=inflater.inflate(R.layout.fragment_b,container,false);        return view;    }//    @Override//    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {//        super.onViewCreated(view, savedInstanceState);//    }}

(2)xml文件

1、activity_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">    <Button        android:id="@+id/change"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="切换到BFragment"        android:textAllCaps="false"/>    <Button        android:id="@+id/transmit"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="传值给AFragment"        android:textAllCaps="false"/>    <TextView        android:id="@+id/textview"        android:layout_width="wrap_content"        android:layout_height="wrap_content" />    <FrameLayout        android:id="@+id/fragment"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:background="#b7e3fc"/></LinearLayout>

2、fragment_a.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:id="@+id/textview"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="A" />    <Button        android:id="@+id/commit"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="AFragment传值给activity"        android:textAllCaps="false" /></LinearLayout>

3、fragment_b.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:id="@+id/textview"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="B"/></LinearLayout>

(3)截图

  • 切换到BFragment

image.png

  • 在activity中把hello传给AFragment

image.png

  • 从AFragment中传递数据给activity

image.png

三、实例化单个fragment

(1)java文件

  • 1、Main2Activity.java
package com.lcfu1.all;import android.support.v4.app.Fragment;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;public class Main2Activity extends SingleFragmentActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main2);    }    //createFragment()抽象方法返回fragment实例    @Override    protected Fragment createFragment() {        return new SingleFragment();    }}
  • 2、SingleFragmentActivity.java
package com.lcfu1.all;import android.os.Bundle;import android.support.annotation.LayoutRes;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentManager;import android.support.v7.app.AppCompatActivity;public abstract class SingleFragmentActivity extends AppCompatActivity {    protected abstract Fragment createFragment();    @LayoutRes    protected int getLayoutResId() {        return R.layout.activity_single_fragment;    }    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(getLayoutResId());        FragmentManager fm = getSupportFragmentManager();        Fragment fragment = fm.findFragmentById(R.id.fragment_container);        if (fragment == null) {            fragment = createFragment();            fm.beginTransaction()                    .add(R.id.fragment_container, fragment)                    .commit();        }    }}
  • 3、SingleFragment.java
package com.lcfu1.all;import android.os.Bundle;import android.support.annotation.Nullable;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;/** * Created by cf on 2017/12/20. */public class SingleFragment extends Fragment {    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {        View view=inflater.inflate(R.layout.fragment_single,container,false);        return view;    }}

(2)xml文件

  • 1、activity_main2.xml
<FrameLayout    xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/fragment_container"    android:layout_width="match_parent"    android:layout_height="match_parent"></FrameLayout>
  • 2、activity_single_fragment.xml
<?xml version="1.0" encoding="utf-8"?><FrameLayout  xmlns:android="http://schemas.android.com/apk/res/android"  android:id="@+id/fragmentContainer"  android:layout_width="match_parent"  android:layout_height="match_parent"  />
  • 3、fragment_single.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:id="@+id/textview"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="SingleFragment"/></LinearLayout>

(3)截图

image.png

原创粉丝点击