• fragment的使用


    http://blog.csdn.net/harvic880925/article/details/44927375

     http://blog.csdn.net/harvic880925/article/details/44948027

    fragment的管理

    1、新建两个fragment1.xml 和 fragment2.xml:

    fragment1.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ff00f0"
        android:orientation="vertical" >
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="This is fragment 1"
            android:textColor="#000000"
            android:textSize="25sp" />
    
    </LinearLayout>

     fragment2.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ffff00"
        android:orientation="vertical" >
    
        <TextView
            android:id="@+id/fragment2_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="This is fragment 2"
            android:textColor="#000000"
            android:textSize="25sp" />
    
    </LinearLayout>

    2、建立对应的Fragment类:Fragment1和Fragment2

    Fragment1:

    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    
    public class Fragment1 extends Fragment {
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            return inflater.inflate(R.layout.fragment1, container, false);
        }
    
    }

    Fragment2:

    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    
    public class Fragment2 extends Fragment {
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            return inflater.inflate(R.layout.fragment2, container, false);
        }
    }

    3、MainActivity的布局

    activity_main.xml

    <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/btn_add_frag1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="ADD  Fragment1" />
    
        <Button
            android:id="@+id/btn_add_frag2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="ADD  Fragment2" />
    
        <Button
            android:id="@+id/btn_remove_frag2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Remove  Fragment2" />
    
        <Button
            android:id="@+id/btn_repalce_frag1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="replace  Fragment1" />
    
        <FrameLayout
            android:id="@+id/fragment_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    
    </LinearLayout>

    4、MainActivity的实现:

    import java.util.ArrayList;
    import java.util.List;
    
    import android.graphics.Color;
    import android.os.Bundle;
    import android.app.Activity;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentActivity;
    import android.support.v4.app.FragmentManager;
    import android.support.v4.app.FragmentTransaction;
    import android.support.v4.view.GravityCompat;
    import android.support.v4.widget.DrawerLayout;
    import android.support.v4.widget.DrawerLayout.DrawerListener;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.MotionEvent;
    import android.view.View;
    import android.view.View.OnTouchListener;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.ListView;
    import android.widget.RelativeLayout;
    import android.widget.TextView;
    
    public class MainActivity extends FragmentActivity {
    
        /** DrawerLayout */
        private DrawerLayout mDrawerLayout;
        /** 左边栏 */
        private RelativeLayout leftLayout;
        /** 右边栏 */
        private RelativeLayout rightLayout;
        /** 左边栏菜单 */
        private ListView mMenuListView;
        /** 菜单列表 */
        private String[] mMenuTitles = {"新闻","订阅","图片","视频","跟帖","投票"};
    
        private List<ContentModel> list;
    
        private ContentAdapter adapter;
    
        private Button button1;
    
        private Button button2;
    
        private Button button3;
    
        private Button button4;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            button1 = (Button) findViewById(R.id.btn_add_frag1);
            button2 = (Button) findViewById(R.id.btn_add_frag2);
            button3 = (Button) findViewById(R.id.btn_remove_frag2);
            button4 = (Button) findViewById(R.id.btn_repalce_frag1);
    
            button1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    
                    Fragment1 fragment1 = new Fragment1();
                    addFragment(fragment1, "fragment1");
                }
            });
    
            button2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    
                    Fragment2 fragment2 = new Fragment2();
                    addFragment(fragment2, "fragment2");
                }
            });
    
            button3.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    
                    removeFragment2();
                }
            });
    
            button4.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    
                    replaceFragment1();
                }
            });
    
    /*        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
            leftLayout=(RelativeLayout) findViewById(R.id.left);
            rightLayout=(RelativeLayout) findViewById(R.id.right);
            mMenuListView =(ListView) leftLayout.findViewById(R.id.left_listview);
    
            initData();
            adapter=new ContentAdapter(this, list);
            mMenuListView.setAdapter(adapter);
            mMenuListView.setOnItemClickListener(new DrawerItemClickListener());*/
        }
    
        private void initData() {
            list=new ArrayList<ContentModel>();
    
            list.add(new ContentModel(R.drawable.doctoradvice2, mMenuTitles[0]));
            list.add(new ContentModel(R.drawable.infusion_selected, mMenuTitles[1]));
            list.add(new ContentModel(R.drawable.mypatient_selected, mMenuTitles[2]));
            list.add(new ContentModel(R.drawable.mywork_selected, mMenuTitles[3]));
            list.add(new ContentModel(R.drawable.nursingcareplan2, mMenuTitles[4]));
            list.add(new ContentModel(R.drawable.personal_selected, mMenuTitles[5]));
        }
    
        /**
         * ListView上的Item点击事件
         *
         */
        private class DrawerItemClickListener implements ListView.OnItemClickListener {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selectItem(position);
            }
        }
    
    
        /**
         * 切换主视图区域的Fragment
         *
         * @param position
         */
        private void selectItem(int position) {
            // TODO Auto-generated method stub
            Fragment fragment = new ContentFragment();
            Bundle args = new Bundle();
            switch (position) {
                case 0:
                    args.putString("key", mMenuTitles[position]);
                    break;
                case 1:
                    args.putString("key", mMenuTitles[position]);
                    break;
                case 2:
                    args.putString("key", mMenuTitles[position]);
                    break;
                case 3:
                    args.putString("key", mMenuTitles[position]);
                    break;
                case 4:
                    args.putString("key", mMenuTitles[position]);
                    break;
                case 5:
                    args.putString("key", mMenuTitles[position]);
                    break;
                default:
                    break;
            }
            fragment.setArguments(args); // FragmentActivity将点击的菜单列表标题传递给Fragment
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.fragment_layout, fragment).commit();
    
            // 更新选择后的item和title,然后关闭菜单
            mMenuListView.setItemChecked(position, true);
            setTitle(mMenuTitles[position]);
            mDrawerLayout.closeDrawer(mMenuListView);
        }
    
        private void addFragment(Fragment fragment, String tag) {
            FragmentManager manager = getSupportFragmentManager();
            FragmentTransaction transaction = manager.beginTransaction();
            transaction.add(R.id.fragment_container, fragment, tag);
            transaction.commit();
        }
    
        private void removeFragment2() {
            FragmentManager manager = getSupportFragmentManager();
            Fragment fragment = manager.findFragmentByTag("fragment2");
            FragmentTransaction transaction = manager.beginTransaction();
            transaction.remove(fragment);
            transaction.commit();
        }
    
        private void replaceFragment1() {
            FragmentManager manager = getSupportFragmentManager();
            Fragment2 fragment2 = new Fragment2();
            FragmentTransaction transaction = manager.beginTransaction();
            transaction.replace(R.id.fragment_container, fragment2);
            transaction.commit();
        }
    
    }

    fragment切换:

    button4.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    
                    Fragment1 fragment1 = new Fragment1();
                    FragmentManager manager = getSupportFragmentManager();
                    FragmentTransaction transaction = manager.beginTransaction();
                    transaction.replace(R.id.fragment_container,fragment1);
                    transaction.commit();
                }
            });

    fragment之间传递信息:

    http://blog.csdn.net/harvic880925/article/details/44131865

     

    Fragment1中点击,跳到Fragment2

    Fragment1.java

    public class Fragment1 extends Fragment {
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment1, container, false);
            Button btn = (Button)view.findViewById(R.id.load_fragment2_btn);
            btn.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(final View view) {
                    Fragment2 fragment2 = new Fragment2();
                    
                    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    
                    transaction.add(R.id.main_layout, fragment2);
                    transaction.addToBackStack(null);
                    transaction.commit();
                }
            });
            return view;
        }
    }

    Fragment2.java

    public class Fragment2 extends Fragment implements View.OnClickListener {
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment2, container, false);
            return view;
        }
    
    }

    二、Fragment间参数传递

    在Fragment2中,新建一个函数:newInstance(String  text)来接收传过来的参数:

    新建一个Fragment2实例,然后将参数通过SetArguments设置到其中;

        public static Fragment2 newInstance(String text) {
            Fragment2 fragment = new Fragment2();
            Bundle args = new Bundle();
            args.putString("param", text);
            fragment.setArguments(args);
            return fragment;
        }

    然后在Fragment2的OnCreateView的时候再从arguments中获取参数:

    public class Fragment1 extends Fragment {
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment1, container, false);
            Button btn = (Button)view.findViewById(R.id.load_fragment2_btn);
            btn.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(final View view) {
                    Fragment2 fragment2 = Fragment2.newInstance("从Fragment1传来的参数");
    
                    FragmentTransaction transaction = getFragmentManager().beginTransaction();
                    transaction.add(R.id.main_layout, fragment2);
                    transaction.addToBackStack(null);
                    transaction.commit();
                }
            });
            return view;
        }
    }

    在Fragment1中,在调起Fragmen2t时,通过调用newInstance函数来获取实例并传递参数:

    public class Fragment1 extends Fragment {
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment1, container, false);
            Button btn = (Button)view.findViewById(R.id.load_fragment2_btn);
            btn.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(final View view) {
                    Fragment2 fragment2 = Fragment2.newInstance("从Fragment1传来的参数");
    
                    FragmentTransaction transaction = getFragmentManager().beginTransaction();
                    transaction.add(R.id.main_layout, fragment2);
                    transaction.addToBackStack(null);
                    transaction.commit();
                }
            });
            return view;
        }
    }

    (三)、从Fragment2向Fragment1回传参数

    Fragment2:

    public class Fragment2 extends Fragment implements View.OnClickListener
    {
        public interface ICustomDialogEventListener {
            public void customDialogEvent(int selectID);
        }
    
        private ICustomDialogEventListener mCustomDialogEventListener;
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment2, container, false);
            if (getArguments() != null) {
                String mParam1 = getArguments().getString("param");
                TextView tv =  (TextView)view.findViewById(R.id.textview);
                tv.setText(mParam1);
            }
            view.findViewById(R.id.img1).setOnClickListener(this);
            view.findViewById(R.id.img2).setOnClickListener(this);
            view.findViewById(R.id.img3).setOnClickListener(this);
            view.findViewById(R.id.img4).setOnClickListener(this);
            return view;
        }
    
        public static Fragment2 newInstance(String text) {
            Fragment2 fragment = new Fragment2();
            Bundle args = new Bundle();
            args.putString("param", text);
            fragment.setArguments(args);
            return fragment;
        }
    
        /**
         * 回调结果值
         * @param listener
         */
        public void setResultListener(ICustomDialogEventListener listener){
            mCustomDialogEventListener = listener;
        }
    
        @Override
        public void onClick(View view) {
            int id = view.getId();
            switch (id){
                case R.id.img1:{
                    mCustomDialogEventListener.customDialogEvent(R.drawable.animal1);
                }
                break;
                case R.id.img2:{
                    mCustomDialogEventListener.customDialogEvent(R.drawable.animal2);
                }
                break;
                case R.id.img3:{
                    mCustomDialogEventListener.customDialogEvent(R.drawable.animal3);
                }
                break;
                case R.id.img4:{
                    mCustomDialogEventListener.customDialogEvent(R.drawable.animal4);
                }
                break;
            }
            //退出当前fragment
            getFragmentManager().popBackStack();
        }
    }

    Fragment1的onClick

    public void onClick(final View view) {
    
                        Fragment2 fragment2 = Fragment2.newInstance("从Fragment1传来的参数");
    
    
                        fragment2.setResultListener(new Fragment2.ICustomDialogEventListener() {
                            @Override
                            public void customDialogEvent(int selectID) {
                                ImageView imageView = (ImageView)getView().findViewById(R.id.img_result);
                                imageView.setImageResource(selectID);
                            }
                        });
    
                        FragmentTransaction transaction = getFragmentManager().beginTransaction();
    
                        transaction.add(R.id.main_layout, fragment2);
                        transaction.addToBackStack(null);
                        transaction.commit();
                    }

    Fragment间参数传递

    http://blog.csdn.net/harvic880925/article/details/44966913

    方法三:在各自的fragment中操作

    1、Fragment2设置textView函数:
    先看个简单的,fragment2中的处理代码:

    public class Fragment2 extends Fragment {
        private TextView mTv;
        …………
        public void setText(String text) {
            mTv.setText(text);
        }
    }

    2、Fragment1中的处理方式:
    (1)、定义接口及变量
    由于是用回调,所以要先定义一个接口及对应的变量:

    private titleSelectInterface mSelectInterface;
     
    public interface titleSelectInterface{
        public void onTitleSelect(String title);
    }

    (2)、接口变量赋值
    接口是给activity用的,所以要在activity中给这里的接口变量赋值,可以有很多方法,当然可以选择写一个setXXX()函数来赋值,但如果用户忘了怎么办?所以我们要强制用户赋值。所以采用强转的方式,在fragment与activity相关联时,进行强转赋值:

    public void onAttach(Activity activity) {
        super.onAttach(activity);
    
        try {
            mSelectInterface = (titleSelectInterface) activity;
        } catch (Exception e) {
            throw new ClassCastException(activity.toString() + "must implement OnArticleSelectedListener");
        }
    }

    采用强转的方式的问题在于,如果用户的activity没有implements titleSelectInterface,就会抛出错误,所以在调试过程中就会发现。
    (3)、调用接口变量
    下一步就是在fragment1中在用户点击listView的item的时候,将结果回传给Activity了,代码如下:

    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    
        listView = (ListView) getView().findViewById(R.id.list);//获取自己视图里的控件引用,方法二
        ArrayAdapter arrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, mStrings);
        listView.setAdapter(arrayAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String str = mStrings[position];
                mSelectInterface.onTitleSelect(str);
            }
        });
    }

    (4)、在Activity中实现titleSelectInterface接口
    首先是MainActivity必须实现titleSelectInterface接口,然后结果会在onTitleSelect(String title)中返回,在结果返回后利用fragment2.setText()操作textView;代码如下:

    public class MainActivity extends FragmentActivity implements Fragment1.titleSelectInterface {
    
        ……
        
        @Override
        public void onTitleSelect(String title) {
            FragmentManager manager = getSupportFragmentManager();
            Fragment2 fragment2 = (Fragment2)manager.findFragmentById(R.id.fragment2);
            fragment2.setText(title);
        }
    }

    在上面代码中可以看出,在结果返回后,通过findFragmentById()来获得fragment2的实例,这里首次出现了findFragmentById()函数的用法,这个函数主要用来静态添加的fragment中,通过fragment的ID值来获取它的实例。在获得fragment2的实例以后,通过调用我们写好了setText()方法来将结果显示在textView中。

    Fragment2 fragment2 = (Fragment2)manager.findFragmentById(R.id.fragment2);

    完整版:

    Fragment1

    public class Fragment1 extends Fragment
    {
        private titleSelectInterface mSelectInterface;
    
        private String[] mStrings = {"Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi",
                "Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag", "Airedale", "Aisy Cendre",
                "Allgauer Emmentaler", "Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi",
                "Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag", "Airedale", "Aisy Cendre",
                "Allgauer Emmentaler"};
    
        private ListView listView;
    
        public interface titleSelectInterface{
            public void onTitleSelect(String title);
        }
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
                View view = inflater.inflate(R.layout.fragment1, container, false);
                return view;
        }
    
        public void onAttach(Activity activity) {
            super.onAttach(activity);
    
            try {
                mSelectInterface = (titleSelectInterface) activity;
            } catch (Exception e) {
                throw new ClassCastException(activity.toString() + "must implement OnArticleSelectedListener");
            }
        }
    
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
    
            listView = (ListView) getView().findViewById(R.id.list);//获取自己视图里的控件引用,方法二
            ArrayAdapter arrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, mStrings);
            listView.setAdapter(arrayAdapter);
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String str = mStrings[position];
                    mSelectInterface.onTitleSelect(str);
                }
            });
        }
    }

    Fragment2

    public class Fragment2 extends Fragment
    {
    
        private TextView mTv;
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment2, container, false);
            return view;
        }
    
        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            mTv = (TextView) getView().findViewById(R.id.fragment2_tv);
        }
    
        public void setText(String text) {
            mTv.setText(text);
        }
    
    
    }

    Mainactivity

    public class MainActivity extends FragmentActivity implements Fragment1.titleSelectInterface {
    
        /**
         * DrawerLayout
         */
        private DrawerLayout mDrawerLayout;
        /**
         * 左边栏
         */
        private RelativeLayout leftLayout;
        /**
         * 右边栏
         */
        private RelativeLayout rightLayout;
        /**
         * 左边栏菜单
         */
        private ListView mMenuListView;
        /**
         * 菜单列表
         */
        private String[] mMenuTitles = {"新闻", "订阅", "图片", "视频", "跟帖", "投票"};
    
        private List<ContentModel> list;
    
        private ContentAdapter adapter;
    
        private Button button1;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    
        @Override
        public void onTitleSelect(String title) {
            FragmentManager manager = getSupportFragmentManager();
            Fragment2 fragment2 = (Fragment2) manager.findFragmentById(R.id.fragment2);
            fragment2.setText(title);
        }
    }
  • 相关阅读:
    java项目部署到LIINUX
    JAVA项目部署(1)
    JAVA项目服务器部署
    JAVA项目部署到云服务器
    JAVA项目打包
    java项目部署
    NHibernate NHibernate使用时误区
    访问其他电脑的c盘
    unit vs单元测试
    java 获取url及url参数解析
  • 原文地址:https://www.cnblogs.com/qlky/p/5415679.html
Copyright © 2020-2023  润新知