Android——Fragment和Activity之间的通信+Frangment生命周期

来源:互联网 发布:含金量高的证书 知乎 编辑:程序博客网 时间:2024/06/16 00:19

Android——Fragment和Activity之间的通信+Frangment生命周期


Fr'agmentActivity之间的通信

1.Fragment中声明一个接口。

2.Activity中实现在Fargment中声明的接口。

3.Fragment中声明一个接口对象。

4.Frangment的生命周期Onattach方法中判断当前Activity是否实现了此Fragment中声明的接口。如果已实现,就把当前Activity转换成接口对象。

5.调用Activity中实现的方法=>(接口对象.方法名)


package com.example.jreduch05;import android.os.Bundle;import android.support.v4.app.Fragment;import android.support.v7.app.AppCompatActivity;import com.example.jreduch05.fragment.FirstFragment;import com.example.jreduch05.fragment.LeftFragment;import com.example.jreduch05.fragment.SecondFragment;public class Fragment1Activity extends AppCompatActivity implements LeftFragment.OnFragmentInteractionListener{    private Fragment fragment1;    private Fragment fragment2;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_fragment1);        getSupportActionBar().hide();    }    @Override    public void changeFragment(int which) {        if (which==1){            fragment1=new FirstFragment();            getSupportFragmentManager()                    .beginTransaction()                    .replace(R.id.fl,fragment1)                    .commit();        }else  if (which==2){            fragment2=new SecondFragment();            getSupportFragmentManager()                    .beginTransaction()                    .replace(R.id.fl,fragment2)                    .commit();        }        else  if (which==3){            if(fragment2!=null && !fragment2.isHidden()){                getSupportFragmentManager().beginTransaction()                        .hide(fragment2).commit();            }        }        else  if (which==4){            if(fragment2!=null && fragment2.isHidden()){                getSupportFragmentManager().beginTransaction()                        .show(fragment2).commit();            }        }    }}
<?xml version="1.0" encoding="utf-8"?><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.jreduch05.Fragment1Activity"><fragment    android:layout_width="match_parent"    android:layout_height="120dp"    android:id="@+id/top"    android:name="com.example.jreduch05.fragment.TopFragment"    ></fragment>    <fragment        android:layout_width="150dp"        android:layout_height="match_parent"        android:id="@+id/left"        android:name="com.example.jreduch05.fragment.LeftFragment"        android:layout_alignTop="@+id/fl"        android:layout_alignParentStart="true"></fragment>    <!--<fragment-->        <!--android:layout_width="250dp"-->        <!--android:layout_height="match_parent"-->        <!--android:id="@+id/main"-->        <!--android:name="com.example.jreduch05.fragment.MainFragment"-->        <!--android:layout_below="@+id/top"-->        <!--android:layout_alignParentEnd="true"></fragment>-->    <FrameLayout        android:layout_width="match_parent"        android:layout_height="match_parent"        android:id="@+id/fl"        android:layout_below="@+id/top"        android:layout_toEndOf="@+id/left">    </FrameLayout></RelativeLayout>
LeftFragment
package com.example.jreduch05.fragment;import android.content.Context;import android.os.Bundle;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentTransaction;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.Button;import com.example.jreduch05.R;/** * A simple {@link Fragment} subclass. */public class LeftFragment extends Fragment {private Fragment fragment1;    private Fragment fragment2;    private OnFragmentInteractionListener mListener;    public LeftFragment() {        // Required empty public constructor    }    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,                             Bundle savedInstanceState) {        // Inflate the layout for this fragment      View view= inflater.inflate(R.layout.fragment_left2, container, false);        Button bt1=(Button)view.findViewById(R.id.bt1);        Button bt2=(Button)view.findViewById(R.id.bt2);        Button bt3=(Button)view.findViewById(R.id.bt3);        Button bt4=(Button)view.findViewById(R.id.bt4);        Button bt5=(Button)view.findViewById(R.id.bt5);        Button bt6=(Button)view.findViewById(R.id.bt6);        Button bt7=(Button)view.findViewById(R.id.bt7);        Button bt8=(Button)view.findViewById(R.id.bt8);        bt1.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                //Toast.makeText(getContext(),"点击按钮1",Toast.LENGTH_SHORT).show();                fragment1=new FirstFragment();                FragmentManager fm=getFragmentManager();                FragmentTransaction fr=fm.beginTransaction();   //开始                fr.replace(R.id.fl,fragment1);  //替换                fr.commit();//提交一个事物            }        });        bt2.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                //Toast.makeText(getContext(),"点击按钮1",Toast.LENGTH_SHORT).show();               fragment2=new SecondFragment();                FragmentManager fm=getFragmentManager();                FragmentTransaction fr=fm.beginTransaction();   //开始                fr.replace(R.id.fl,fragment2);  //替换                fr.commit();//提交一个事物            }        });        bt3.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                mListener.changeFragment(1);            }        });        bt4.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                mListener.changeFragment(2);            }        });        bt5.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                if(fragment1!=null && !fragment1.isHidden()){                    getFragmentManager().beginTransaction()                            .hide(fragment1).commit();                }            }        });        bt6.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                if(fragment1!=null && fragment1.isHidden()){                    getFragmentManager().beginTransaction()                            .show(fragment1).commit();                }            }        });        bt7.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                mListener.changeFragment(3);            }        });        bt8.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                mListener.changeFragment(4);            }        });        return  view;    }    public interface OnFragmentInteractionListener {        // TODO: Update argument type and name        void changeFragment(int which);    }    @Override    public void onAttach(Context context) {        super.onAttach(context);        if (context instanceof OnFragmentInteractionListener) {            mListener = (OnFragmentInteractionListener) context;        } else {            throw new RuntimeException(context.toString()                    + " must implement OnFragmentInteractionListener");        }    }}
<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"    android:background="#0c04f7"    tools:context="com.example.jreduch05.fragment.LeftFragment">    <!-- TODO: Update blank fragment layout -->    <!--<TextView-->        <!--android:layout_width="match_parent"-->        <!--android:layout_height="match_parent"-->        <!--android:background="#0c04f7"-->        <!--android:id="@+id/left"-->        <!--android:text="leftfragment"-->        <!--android:textSize="30sp"-->        <!--android:gravity="center"/>-->    <LinearLayout        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:orientation="vertical"        >    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="第一个Fragment"        android:id="@+id/bt1"        />    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="第二个Fragment"        android:id="@+id/bt2"        />        <Button            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="第一个Fragment\n(Activity通信)"            android:id="@+id/bt3"            />        <Button            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="第二个Fragment\n(Activity通信)"            android:id="@+id/bt4"            />        <Button            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="隐藏Fragment1"            android:id="@+id/bt5"            />        <Button            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="显示Fragment1"            android:id="@+id/bt6"/>        <Button            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="隐藏Fragment2\n(Activity通信)"            android:id="@+id/bt7"            />        <Button            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="显示Fragment2\n(Activity通信)"            android:id="@+id/bt8"/>    </LinearLayout></FrameLayout>

FirstFragment

package com.example.jreduch05.fragment;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;import android.widget.TextView;import com.example.jreduch05.R;/** * A simple {@link Fragment} subclass. */public class FirstFragment extends Fragment {    public FirstFragment() {        // Required empty public constructor    }    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,                             Bundle savedInstanceState) {        // Inflate the layout for this fragment        return inflater.inflate(R.layout.fragment_first, container, false);    }    @Override    public void onActivityCreated(@Nullable Bundle savedInstanceState) {        super.onActivityCreated(savedInstanceState);        Bundle bundle=getArguments();        if(bundle!=null){          int ch= bundle.getInt("channel") ;            TextView tv= (TextView) getView().findViewById(R.id.tv);            tv.setText(ch+"");        }    }}

<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.jreduch05.fragment.FirstFragment">    <!-- TODO: Update blank fragment layout -->    <TextView        android:layout_width="match_parent"        android:layout_height="match_parent"        android:text="我是fragment1"        android:textSize="30sp"android:id="@+id/tv"        android:gravity="center"/></FrameLayout>

SecondFragment

package com.example.jreduch05.fragment;import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import com.example.jreduch05.R;/** * A simple {@link Fragment} subclass. */public class SecondFragment extends Fragment {    public SecondFragment() {        // Required empty public constructor    }    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,                             Bundle savedInstanceState) {        // Inflate the layout for this fragment        return inflater.inflate(R.layout.fragment_second, container, false);    }}
<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.jreduch05.fragment.SecondFragment">    <!-- TODO: Update blank fragment layout -->    <TextView        android:layout_width="match_parent"        android:layout_height="match_parent"        android:text="我是fragment2"        android:textSize="30sp"        android:gravity="center"/></FrameLayout>
MainFragment
package com.example.jreduch05.fragment;import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import com.example.jreduch05.R;/** * A simple {@link Fragment} subclass. */public class MainFragment extends Fragment {    public MainFragment() {        // Required empty public constructor    }    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,                             Bundle savedInstanceState) {        // Inflate the layout for this fragment        return inflater.inflate(R.layout.fragment_main, container, false);    }}
<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.jreduch05.fragment.MainFragment">    <!-- TODO: Update blank fragment layout -->    <TextView        android:layout_width="match_parent"        android:layout_height="match_parent"        android:background="#f7ef04"        android:id="@+id/main"        android:text="Mainfragment"        android:textSize="30sp"        android:gravity="center"/></FrameLayout>
TopFargment

package com.example.jreduch05.fragment;import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import com.example.jreduch05.R;/** * A simple {@link Fragment} subclass. */public class TopFragment extends Fragment {    public TopFragment() {        // Required empty public constructor    }    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,                             Bundle savedInstanceState) {        // Inflate the layout for this fragment        return inflater.inflate(R.layout.fragment_top, container, false);    }}
<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.jreduch05.fragment.TopFragment">    <!-- TODO: Update blank fragment layout -->    <TextView        android:layout_width="match_parent"        android:layout_height="match_parent"        android:background="#f50f0f"        android:text="Topfragment"        android:textSize="30sp"        android:id="@+id/top"        android:gravity="center"/></FrameLayout>



Frangment生命周期




方法名 说明
onAttach () Fragment被附加到Activity的时,调用此函数,在这个方法中可以获得宿主Activity。
onCreate () Fragment被创建的时,调用此函数。
onCreateView () Fragment的布局加载时,调用此函数。
onActivityCreated () 当宿主Activity启动完毕后,调用此函数。
onStart () 启动Fragment时,调用此函数。
onResume () Fragment恢复时,调用此函数。
onPause () Fragment暂停时,调用此函数。
onStop() Fragment停止时,调用此函数。
onDestroyView() 销毁Fragment中的View控件时,调用此函数。
onDestroy() 销毁Fragment时,调用此函数。
onDetach() Fragment从Activity脱离时,调用此函数 

启动


Remove


回退


3键



<span style="font-size:18px;">package com.example.jreduch05;import android.os.Bundle;import android.support.v4.app.Fragment;import android.support.v7.app.AppCompatActivity;import android.util.Log;import android.view.View;import android.widget.Button;import com.example.jreduch05.fragment.FirstFragment;import com.example.jreduch05.fragment.LifeFragment;public class FragmentLifeActivity extends AppCompatActivity {    //private Fragment fragment;    private Fragment fragment2;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_fragment_life);       final Fragment fragment=new LifeFragment();        Button bt1=(Button)findViewById(R.id.bt_remove);        Button bt2=(Button)findViewById(R.id.bt_replace);        Button bt3=(Button)findViewById(R.id.bt_hide);        Button bt4=(Button)findViewById(R.id.bt_show);        Button bt5=(Button)findViewById(R.id.bt_remrep);        bt1.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                if (fragment!=null){                    getSupportFragmentManager().beginTransaction()                            .remove(fragment).commit();                }            }        });        bt2.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                if (fragment!=null){                    fragment2=new FirstFragment();                    Bundle bundle=new Bundle();                    bundle.putInt("channel",1261911);                    fragment2.setArguments(bundle);                    getSupportFragmentManager().beginTransaction()                            .replace(R.id.life_frame, fragment2).commit();                }            }        });        bt3.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                if (fragment!=null&&!fragment.isHidden()){                    getSupportFragmentManager().beginTransaction()                            .hide(fragment).commit();                }            }        });        bt4.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                if (fragment!=null&&fragment.isHidden()){                    getSupportFragmentManager().beginTransaction()                            .show(fragment).commit();                }            }        });        bt5.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                if (fragment2!=null){                    getSupportFragmentManager().beginTransaction()                            .remove(fragment2).commit();                }            }        });        getSupportFragmentManager()                .beginTransaction()                .replace(R.id.life_frame, fragment)                .commit();        Log.d("====Activity==", "onCreate");    }    @Override    protected void onStart() {        super.onStart();        Log.d("====Activity==", "onStart");    }    @Override    protected void onRestart() {        super.onRestart();        Log.d("====Activity==", "onRestart");    }    @Override    protected void onResume() {        super.onResume();        Log.d("====Activity==", "onRestart");    }    @Override    protected void onPause() {        super.onPause();        Log.d("====Activity==", "onPause");    }    @Override    protected void onStop() {        super.onStop();        Log.d("====Activity==", "onStop");    }    @Override    protected void onDestroy() {        super.onDestroy();        Log.d("====Activity==", "onDestroy");    }}</span>
<?xml version="1.0" encoding="utf-8"?><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.jreduch05.FragmentLifeActivity">    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/bt_remove"        android:text="Remove Fragment"        android:gravity="center"/>    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/bt_replace"        android:text="Replace Fragment"        android:layout_below="@+id/bt_remove"        android:gravity="center"/>    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/bt_hide"        android:layout_below="@+id/bt_replace"        android:text="Hide Fragment"        android:gravity="center"/>    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@+id/bt_hide"        android:id="@+id/bt_show"        android:text="Show Fragment"        android:gravity="center"/>    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@+id/bt_show"        android:id="@+id/bt_remrep"        android:text="removereplace"        android:gravity="center"/>    <FrameLayout        android:layout_width="match_parent"        android:layout_height="match_parent"        android:id="@+id/life_frame"        android:layout_below="@+id/bt_remrep">    </FrameLayout></RelativeLayout>




作者:冲天之峰      20160808





3 0
原创粉丝点击