fragment的那些使用

2019-01-17  本文已影响0人  刘孙猫咪

fragment的静态使用:

fragment的静态使用就是在activity的xml布局中把fragment控件来使用,利用name属性设置对应fragment的路径,静态使用时要注意给fragment加id,不加id运行会报错

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/colorAccent"
        android:text="标题"
        android:gravity="center"
        android:textColor="@android:color/white"
        android:textSize="20sp"/>
    <fragment
        android:id="@+id/fragment_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:name="com.lsm.myapplication.fragment.ContentFragment"/>

</LinearLayout>

运行效果和平时动态使用的效果是一样的;


GIF.gif

上面就是fragment的静态使用方式,接下来是它的动态使用方式;

fragment的动态使用:

fragment的动态使用就是利用FragmentManager和FragmentTransaction将对应的fragment与activity布局中对应的id相关联,将对应的fragment添加进去,这也是平时开发中使用的比较多的一种方式;

FragmentManager fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction.add(R.id.content_layout,new ContentFragment());
transaction.commit();

对于这段代码都不陌生,FragmentTransaction还提供了replace、remove等一系列操作fragment的方法,动态使用和静态使用的效果是一样的;

fragment和activity之间的传值:

activity传值给fragment:
在activity中利用setArguments传值,在fragment利用getArguments获取传递过来的值;

//传递值
private void activityToFragment(){
        String trim = etContent.getText().toString().trim();
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        ContentFragment contentFragment = new ContentFragment();
        //利用setArguments Bundle传值
        Bundle bundle=new Bundle();
        bundle.putString("trim",trim);
        contentFragment.setArguments(bundle);
        transaction.replace(R.id.content_layout,contentFragment);
        transaction.commit();
    }
//获取值
Bundle bundle = getArguments();
if(bundle!=null){
    String trim = bundle.getString("trim");
    etContent.setText(trim);
}
GIF.gif

fragment给activity传值:
fragment给activity传值可以采用接口回调的方式,就是在对应的fragment里面定义一个接口,在需要传递的地方进行回调,在对应的activity中实现该接口,并重写该方法,在方法中获取fragment传递过来的值;

public class ContentFragment extends Fragment {
    private EditText etContent;
    private ContentInterface linstener;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        //初始化接口
        linstener= (ContentInterface) context;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_content,container,false);
        etContent=view.findViewById(R.id.et_content);
        Bundle bundle = getArguments();
        if(bundle!=null){
            String trim = bundle.getString("trim");
            etContent.setText(trim);
        }

        view.findViewById(R.id.tv_send).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fragmentToActivity();
            }
        });
        return view;
    }
    private void fragmentToActivity(){
        if(linstener!=null){
            //进行传值
            linstener.sendContent(etContent.getText().toString().trim());
        }
    }

    /**
     * 定义该接口用户fragment向activity传值使用
     */
    public interface ContentInterface{
        void sendContent(String content);
    }
}
public class MainActivity extends AppCompatActivity implements ContentFragment.ContentInterface {
    private EditText etContent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        etContent=findViewById(R.id.et_content);
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        transaction.add(R.id.content_layout,new ContentFragment());
        transaction.commit();

        findViewById(R.id.tv_send).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                activityToFragment();
            }
        });
    }
    private void activityToFragment(){
        String trim = etContent.getText().toString().trim();
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        ContentFragment contentFragment = new ContentFragment();
        //利用setArguments Bundle传值
        Bundle bundle=new Bundle();
        bundle.putString("trim",trim);
        contentFragment.setArguments(bundle);
        transaction.replace(R.id.content_layout,contentFragment);
        transaction.commit();
    }

    @Override
    public void sendContent(String content) {
        if(content!=null&&content.length()!=0){
            //获取fragment传递过来的值
            etContent.setText(content);
        }

    }
}

GIF.gif

fragment和fragment之间的传值:

activity 布局采用的是fragment的静态使用,左右两边各一个fragment;

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context=".MainActivity">

    <fragment
        android:id="@+id/left_fragment"
        android:name="com.lsm.myapplication.fragment.LeftFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />

    <fragment
        android:id="@+id/right_fragment"
        android:name="com.lsm.myapplication.fragment.RightFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />

</LinearLayout>

传值方式一:
在进行传值时通过getFragmentManager().findFragmentById或者getFragmentManager().findFragmentByTag()获取到右边的fragment,在右边的fragment提供一个public方法,方法里面进行设置操作;

private void leftToRight(){
        RightFragment fragment = (RightFragment) getFragmentManager().findFragmentById(R.id.right_fragment);
        fragment.setContent(etContent.getText().toString().trim());
    }
/**
     * 设置内容
     * @param content
     */
    public void setContent(String content){
        etContent.setText(content);
    }

方式二:
通过getFragmentManager().findFragmentById或者getFragmentManager().findFragmentByTag()获取到右边的fragment,在通过getView方法直接获取到右边fragment中的布局view通过view.findViewById获取到对应的view,对获取到的view进行赋值操作;

private void leftToRight(){
        RightFragment fragment = (RightFragment) getFragmentManager().findFragmentById(R.id.right_fragment);
        View fragmentView = fragment.getView();
        EditText rightEdit = fragmentView.findViewById(R.id.et_content);
        rightEdit.setText(etContent.getText().toString().trim());
    }

方式三:
直接通过getActivity().findViewById根据id获取到对应的view,对获取到的view进行赋值;这种方式需要注意左边fragment有右边fragment中的控件id不要存在一样的;

private void leftToRight(){
//        RightFragment fragment = (RightFragment) getFragmentManager().findFragmentById(R.id.right_fragment);
        EditText rightEdit = getActivity().findViewById(R.id.right_content);
        rightEdit.setText(etContent.getText().toString().trim());
    }
GIF.gif

ListFragment

ListFragment extends Fragment,同时里面封装了一个ListView,就是一个列表Fragment,如果项目中有类似的需求可以使用ListFragment可以少写一些代码;使用时和ListView和RecyclerView一样在对应的Fragment xml布局中使用,不过在设置id的时候需要注意,要使用系统给的id,不能随便设置id

<?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">
    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>

设置好系统id后,在Fragment不需要通过findViewById获取控件,可以直接通过setAdapter设置适配器数据;

//设置适配器
setListAdapter(new ItemAdapter());

在设置点击事件时和之前也不一样,需要重写onListItemClick方法,在该方法中处理条目点击事件;

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        Toast.makeText(getActivity(),"点击了:"+position,Toast.LENGTH_LONG).show();
}

完整代码:

public class FragmentList extends ListFragment {
    private List<String> list;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_list,container,false);
        list=new ArrayList<>();
        for(int i=0;i<20;i++){
            list.add("itemposition"+i);
        }
        //设置适配器
        setListAdapter(new ItemAdapter());

        return view;
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        Toast.makeText(getActivity(),"点击了:"+position,Toast.LENGTH_LONG).show();
    }

    class ItemAdapter extends BaseAdapter{

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

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if(convertView==null){
                viewHolder=new ViewHolder();
                convertView=LayoutInflater.from(getActivity()).inflate(R.layout.item_layout,parent,false);
                viewHolder.itemText=convertView.findViewById(R.id.item_text);
                convertView.setTag(viewHolder);
            }else{
                viewHolder= (ViewHolder) convertView.getTag();
            }
            viewHolder.itemText.setText(list.get(position));
            return convertView;
        }
        class ViewHolder{
            TextView itemText;
        }
    }
}

GIF.gif

DialogFragment

DialogFragment extends Fragment拥有fragment生命周期的一个dialog,相比于系统的dialog,DialogFragment在发生横竖屏切换时,不会被销毁掉,会保持原样,在某些场景下比系统的dialog体验要好;使用和Fragment一样,定义一个类 extend DialogFragment,
可以重写onCreateView方法,通过xml布局来实现一个Dialog;

@Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

也可以onCreateDialog方法,通过创建一个Dialog来实现效果;

@NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        return super.onCreateDialog(savedInstanceState);
    }
public class ContentDialog extends DialogFragment {
//    @Nullable
//    @Override
//    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//        return super.onCreateView(inflater, container, savedInstanceState);
//    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        AlertDialog.Builder builder=new AlertDialog.Builder(getActivity())
                .setTitle("提示")
                .setMessage("是否退出应用程序")
                .setIcon(R.mipmap.ic_launcher)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getActivity(),"点击了取消",Toast.LENGTH_LONG).show();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getActivity(),"点击了确定",Toast.LENGTH_LONG).show();
                    }
                });
        return builder.create();
    }
}

这样子就创建好了一个DialogFragment,使用时直接new 一个DialogFragment,调用它的show方法;

ContentDialog contentDialog=new ContentDialog();
contentDialog.show(getSupportFragmentManager(),"contentDialog");
GIF.gif
上一篇下一篇

猜你喜欢

热点阅读