Android 从Activity中往ViewPager里的fragment传递数据

Posted ~~~周

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android 从Activity中往ViewPager里的fragment传递数据相关的知识,希望对你有一定的参考价值。

android 从Activity中往ViewPager里的fragment传递数据

1.界面展示
在这里插入图片描述
2.界面布局
activity_main.xml

<?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">

    <EditText
        android:id="@+id/e1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:imeOptions="actionSearch"
        android:singleLine="true"
        android:gravity="center"
        android:hint="请输入要传递的值"/>

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/v1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>

fragment_blank.xml

<?xml version="1.0" encoding="utf-8"?>
<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=".BlankFragment">

    <!-- TODO: Update blank fragment layout -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="接受传递的值如下"
        android:textSize="20sp"/>

    <TextView
        android:id="@+id/t1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:padding="10dp"
        android:text=""/>
    </LinearLayout>

</FrameLayout>

3.功能实现

核心代码
在这里插入图片描述
在这里插入图片描述
MainActivity.class

package com.example.note6;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.EditText;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
private EditText e1;
private List<Fragment> fragments;
private ViewPager v1;
private BlankFragment blankFragment;
private Bundle bundle=new Bundle();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        e1=(EditText)findViewById(R.id.e1);
        v1=(ViewPager)findViewById(R.id.v1);
        e1.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                bundle.putString("Result",e1.getText().toString());
                return false;
            }
        });
        FragmentManager fragmentManager=getSupportFragmentManager();
        fragments=new ArrayList<Fragment>();
        blankFragment=(BlankFragment)Fragment.instantiate(this,BlankFragment.class.getName(),bundle);
        fragments.add(blankFragment);
        MyPagerAdapter myPagerAdapter=new MyPagerAdapter(fragmentManager);
        v1.setAdapter(myPagerAdapter);
    }
    public class MyPagerAdapter extends FragmentPagerAdapter
    {

        public MyPagerAdapter(@NonNull FragmentManager fm) {
            super(fm);
        }

        @NonNull
        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

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

}

BlankFragment .class

package com.example.note6;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import java.sql.Time;
import java.util.Timer;
import java.util.TimerTask;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link BlankFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class BlankFragment extends Fragment {
private TextView t1;
private String result;
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public BlankFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment BlankFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static BlankFragment newInstance(String param1, String param2) {
        BlankFragment fragment = new BlankFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view=inflater.inflate(R.layout.fragment_blank, container, false);
        t1=view.findViewById(R.id.t1);
        StartTime();
        return view;
    }
    public void StartTime()
    {
        Timer timer=new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Bundle bundle=getArguments();
                result=bundle.getString("Result");
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        t1.setText(result);
                    }
                });
            }
        },0,100);
    }
}

在这里插入图片描述
4.源代码
点击下载

以上是关于Android 从Activity中往ViewPager里的fragment传递数据的主要内容,如果未能解决你的问题,请参考以下文章

Java中往zip压缩包追加文件

Android从activity2访问activity1

android怎么从一个activity获取另一个activity的信息

sql中往一个表中插入数据但是其中一列需要从另一张表查状态,求指导

android开发 如何从一个activity中的两个按钮分别跳转到另外两个activity?

Android从Fragment跳转到Activity