Fragment使用(下)

相关资料

相关视频:

Fragment应用下

1、Fragment与Activity间的通信

1.1、Activity向所属的Fragment传值

1.1.1、代码实例

Test5FragmentActivity

public class Test5FragmentActivity extends AppCompatActivity {

    private FragmentManager manager;
    private FragmentTransaction transaction;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test5_fragment);

        manager = getFragmentManager();
        transaction = manager.beginTransaction();
        transaction.add(R.id.content_layout, new ResultFragment());
        transaction.commit();

        EditText editText = findViewById(R.id.et_content);


        findViewById(R.id.btn_pass).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String info = editText.getText().toString().trim();
                ResultFragment resultFragment = new ResultFragment();
                Bundle bundle = new Bundle();
                bundle.putString("info", info);
                resultFragment.setArguments(bundle);

                manager = getFragmentManager();
                transaction = manager.beginTransaction();
                transaction.replace(R.id.content_layout, resultFragment);
                transaction.commit();
            }
        });
    }
}

布局文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    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"
    tools:context=".fragment.test5.Test5FragmentActivity">

    <EditText
        android:id="@+id/et_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/hint_content"/>

    <Button
        android:id="@+id/btn_pass"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/light_blue_2e"
        android:text="@string/btn_name"
        android:textSize="20sp"
        android:textColor="@color/white"
        android:layout_below="@+id/et_content"
        android:layout_centerHorizontal="true"
        android:gravity="center"/>

    <LinearLayout
        android:id="@+id/content_layout"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:layout_marginTop="50dp"
        android:layout_below="@+id/btn_pass"
        android:orientation="horizontal"/>

</RelativeLayout>

 ResultFragment

public class ResultFragment extends Fragment {

    @SuppressLint("InflateParams")
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_result, null);
        TextView textView = view.findViewById(R.id.tv_show);
        Bundle bundle = getArguments();
        if (null != bundle) {
            String info = bundle.getString("info");
            textView.setText(info);
        }
        return view;
    }


}

布局文件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rl_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/tv_show"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:text="TEXT"
        android:textColor="@color/light_blue_2e"
        android:textSize="30sp"/>

</RelativeLayout>

1.1.2、总结

 

1.2、所属的Fragment向Activity传值

1.2.1、代码实例

Test6FragmentActivity

public class Test6FragmentActivity extends AppCompatActivity implements ResourceFragment.MyListener {

    private TextView tvShow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test6_fragment);
        tvShow = findViewById(R.id.tv_show);
    }

    @Override
    public void sendMessage(String msg) {
        if (!TextUtils.isEmpty(msg)){
            tvShow.setText(msg);
        }

    }
}

布局文件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    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"
    tools:context=".fragment.test6.Test6FragmentActivity">

    <TextView
        android:id="@+id/tv_show"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Text"
        android:layout_centerHorizontal="true"
        android:textSize="24sp"
        android:gravity="center"
        android:textColor="@color/light_blue_2e"
        android:layout_margin="10dp"
        />

    <fragment
        android:id="@+id/fragment_resource"
        android:name="com.gs.common3.fragment.test6.ResourceFragment"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:layout_below="@id/tv_show"
        android:layout_marginTop="20dp"/>

</RelativeLayout>

ResourceFragment

public class ResourceFragment extends Fragment {

    private EditText etContent;
    private MyListener listener;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /**
         * 创建接口的子类对象
         * 获取当前fragment所属的activity,activity实现了MyListener接口,是其子类
         */
        listener= (MyListener) getActivity();
    }

    @SuppressLint("InflateParams")
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_resource, null);
        etContent = view.findViewById(R.id.et_content);
        Button btnPass = view.findViewById(R.id.btn_pass);
        btnPass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String info = etContent.getText().toString().trim();
                /**
                 * 根据Java中多态的含义,父类的引用指向子类的对象,调用函数时会执行子类的实现
                 */
                listener.sendMessage(info);
            }
        });
        return view;
    }

    public interface MyListener{
        void sendMessage(String msg);
    }
}

 布局文件:

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

    <EditText
        android:id="@+id/et_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入要传递的数据"
        />

    <Button
        android:id="@+id/btn_pass"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_margin="10dp"
        android:text="点击传值"
        android:layout_below="@+id/et_content"
        android:background="@color/light_blue_2e"
        android:textColor="@color/white"
        android:textSize="24sp"/>

</RelativeLayout>

1.2.2、总结

 

2、Fragment与Fragment间的通信

2.1、代码实例

Test7FragmentActivity

public class Test7FragmentActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test7_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=".fragment.test7.Test7FragmentActivity">

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

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

</LinearLayout>

LeftFragment

public class LeftFragment extends Fragment {

    private EditText etContent;

    @SuppressLint("InflateParams")
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_left, null);
        etContent = view.findViewById(R.id.et_content);
        Button btnPass = view.findViewById(R.id.btn_pass);
        btnPass.setOnClickListener(v -> {
            String info = etContent.getText().toString().trim();
            /*
              方式一:可以调用 findFragmentById 根据id的方式获得fragment的对象,调用fragment中的方法赋值
             */
//                RightFragment rightFragment= (RightFragment) getFragmentManager()
//                        .findFragmentById(R.id.right_fragment);
//                rightFragment.setTextView(info);

            /*
             * 方式二:直接获取view控件进行操作
             */
//                TextView tv = getFragmentManager()
//                        .findFragmentById(R.id.right_fragment)
//                        .getView()
//                        .findViewById(R.id.tv_show);
//                tv.setText(info);

            /*
             * 方式三:先调用 getActivity 获取所属activity的对象,然后调用findViewById获取目标控件
             */
            TextView tv=getActivity().findViewById(R.id.tv_show);
            tv.setText(info);

        });
        return view;
    }


}

布局文件:

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

    <EditText
        android:id="@+id/et_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入数据"
        android:layout_centerVertical="true"
        />

    <Button
        android:id="@+id/btn_pass"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_margin="10dp"
        android:text="传值"
        android:layout_below="@+id/et_content"
        android:background="@color/light_blue_2e"
        android:textColor="@color/white"
        android:textSize="24sp"/>

</RelativeLayout>

 RightFragment

public class RightFragment extends Fragment {

    private TextView tvShow;

    @SuppressLint("InflateParams")
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_right, null);
        tvShow = view.findViewById(R.id.tv_show);
        return view;
    }

    public void setTextView(String text){
        tvShow.setText(text);
    }
}

布局文件:

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

    <TextView
        android:id="@+id/tv_show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:text="text"
        android:textColor="@color/light_blue_2e"
        android:textSize="30sp"/>

</RelativeLayout>

 

2.2、总结

3、ListFragment的应用

3.1、代码实例

Test8FragmentActivity

public class Test8FragmentActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test8_fragment);
    }
}

布局文件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context=".fragment.test8.Test8FragmentActivity">

    <fragment
        android:id="@+id/fragment_list"
        android:name="com.gs.common3.fragment.test8.MyListFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

MyListFragment

public class MyListFragment extends ListFragment {

    private List<String> list;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        @SuppressLint("InflateParams")
        View view = inflater.inflate(R.layout.fragment_list, null);
        list = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            list.add("item" + i);
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(),
                android.R.layout.simple_list_item_1, list);
        setListAdapter(adapter);
        return view;
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        Toast.makeText(getActivity(), list.get(position) + "被点击了!",
                Toast.LENGTH_SHORT).show();
    }
}

 布局文件:

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

    <!--如果当前使用的fragment是ListFragment,那么在对应的布局文件中定义的listview标签中id为固定值,值为 @id/android:list android.R.id.list -->
    <ListView
        android:id="@id/android:list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

</RelativeLayout>

3.2、总结

4、DialogFragment的应用

4.1、代码实例

Test9FragmentActivity

public class Test9FragmentActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test9_fragment);

        findViewById(R.id.btn_click).setOnClickListener(v -> {
            MyDialogFragment dialogFragment = new MyDialogFragment();
            dialogFragment.show(getFragmentManager(), "dialog");
        });
    }
}

布局文件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    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"
    tools:context=".fragment.test9.Test9FragmentActivity">

    <Button
        android:id="@+id/btn_click"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="点击显示DialogFragment"
        android:textSize="24sp"
        android:textAllCaps="false"
        android:layout_centerInParent="true"
        android:background="@color/light_blue_2e"
        android:textColor="@color/white"/>

</RelativeLayout>

 MyDialogFragment

public class MyDialogFragment extends DialogFragment {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("提示")
                .setMessage("您确定要退出吗?")
                .setIcon(R.mipmap.ic_launcher)
                .setPositiveButton("确定", (dialog, which) -> {
                    Toast.makeText(getActivity(), "点击了确定", Toast.LENGTH_SHORT).show();
                    dismiss();
                })
                .setNegativeButton("取消", (dialog, which)
                        -> dismiss());
        return builder.create();
    }
}

4.2、总结

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值