【问题标题】:How to transfer some data to another Fragment?如何将一些数据传输到另一个 Fragment?
【发布时间】:2011-11-01 06:19:58
【问题描述】:

如何将一些数据传输到另一个Fragment,同样使用extrasintents 完成?

【问题讨论】:

  • 我尝试回答这个问题@here。我希望它有效。

标签: android android-fragments


【解决方案1】:

使用Bundle。这是一个例子:

Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);

Bundle 为许多数据类型提供了 put 方法。见this

然后在您的Fragment 中,使用以下方法检索数据(例如,在 onCreate() 方法中):

Bundle bundle = this.getArguments();
if (bundle != null) {
        int myInt = bundle.getInt(key, defaultValue);
}

【讨论】:

  • 您好,感谢您的回答,但我们需要实现什么吗?比如 Serializable 或 Parcelable??
  • 不,你不需要实现任何类。
  • 在尝试从中获取任何内容之前,可能需要添加检查以查看该捆绑包!= Null?
  • 如果你在内存中有一个现有的片段?
  • 这是代码不起作用,没有将活动重定向到带有数据的片段
【解决方案2】:

要进一步扩展前面的答案,就像 Ankit 所说的那样,对于复杂的对象,您需要实现 Serializable。例如,对于简单对象:

public class MyClass implements Serializable {
    private static final long serialVersionUID = -2163051469151804394L;
    private int id;
    private String created;
}

在您的 FromFragment 中:

Bundle args = new Bundle();
args.putSerializable(TAG_MY_CLASS, myClass);
Fragment toFragment = new ToFragment();
toFragment.setArguments(args);
getFragmentManager()
    .beginTransaction()
    .replace(R.id.body, toFragment, TAG_TO_FRAGMENT)
    .addToBackStack(TAG_TO_FRAGMENT).commit();

在您的 ToFragment 中:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

    Bundle args = getArguments();
    MyClass myClass = (MyClass) args
        .getSerializable(TAG_MY_CLASS);

【讨论】:

  • 你是最棒的。谢谢
  • @Sameera 我通常只是在我的片段类中放一个字符串,即如果我有类 MyFragmentIMGoingTo.java 那么我的 TAG_TO_FRAGMENT = "MyFragmentIMGoingTo";
  • 更好地使用 Parcelable,因为 google 推荐它作为 android 操作系统更优化的序列化技术。
【解决方案3】:

getArguments() 返回 null,因为“它什么都没有”

试试这段代码来处理这种情况

if(getArguments()!=null)
{
int myInt = getArguments().getInt(key, defaultValue);
}

【讨论】:

  • 您好,感谢您的回答,但我们需要实现什么吗?比如 Serializable 或 Parcelable??
  • 你确定吗?因为当我使用意图在片段和活动之间传递复杂数据时,我必须实现 Serializable/Parcelable ......
  • 我只尝试了简单的值。不知道 Serializable 或 Parcelable 抱歉
  • 应该是评论不回答!!
【解决方案4】:

片段到片段传递数据的完整代码

Fragment fragment = new Fragment(); // replace your custom fragment class 
Bundle bundle = new Bundle();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                bundle.putString("key","value"); // use as per your need
                fragment.setArguments(bundle);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.replace(viewID,fragment);
                fragmentTransaction.commit();

在自定义片段类中

Bundle mBundle = new Bundle();
mBundle = getArguments();
mBundle.getString(key);  // key must be same which was given in first fragment

【讨论】:

【解决方案5】:

只是为了扩展以前的答案 - 它可以帮助某人。如果您的getArguments() 返回null,请将其放入onCreate() 方法而不是片段的构造函数:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    int index = getArguments().getInt("index");
}

【讨论】:

    【解决方案6】:

    这就是你使用 bundle 的方式:

    Bundle b = new Bundle();
    b.putInt("id", id);
    Fragment frag= new Fragment();
    frag.setArguments(b);
    

    从包中检索值:

     bundle = getArguments();
     if (bundle != null) {
        id = bundle.getInt("id");
     }
    

    【讨论】:

      【解决方案7】:

      如果您使用图形在片段之间导航,您可以这样做:从片段 A:

          Bundle bundle = new Bundle();
          bundle.putSerializable(KEY, yourObject);
          Navigation.findNavController(view).navigate(R.id.fragment, bundle);
      

      到片段 B:

          Bundle bundle = getArguments();
          object = (Object) bundle.getSerializable(KEY);
      

      当然你的对象必须实现 Serializable

      【讨论】:

      • 最好最简单的答案
      【解决方案8】:
                  First Fragment Sending String To Next Fragment
                  public class MainActivity extends AppCompatActivity {
                          private Button Add;
                          private EditText edt;
                          FragmentManager fragmentManager;
                          FragClass1 fragClass1;
      
      
                          @Override
                          protected void onCreate(Bundle savedInstanceState) {
                              super.onCreate(savedInstanceState);
                              setContentView(R.layout.activity_main);
                              Add= (Button) findViewById(R.id.BtnNext);
                              edt= (EditText) findViewById(R.id.editText);
      
                              Add.setOnClickListener(new View.OnClickListener() {
                                  @Override
                                  public void onClick(View v) {
                                      fragClass1=new FragClass1();
                                      Bundle bundle=new Bundle();
      
                                      fragmentManager=getSupportFragmentManager();
                                      fragClass1.setArguments(bundle);
                                      bundle.putString("hello",edt.getText().toString());
                                      FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
                                      fragmentTransaction.add(R.id.activity_main,fragClass1,"");
                                      fragmentTransaction.addToBackStack(null);
                                      fragmentTransaction.commit();
      
                                  }
                              });
                          }
                      }
               Next Fragment to fetch the string.
                  public class FragClass1 extends Fragment {
                        EditText showFrag1;
      
      
                          @Nullable
                          @Override
                          public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
      
                              View view=inflater.inflate(R.layout.lay_frag1,null);
                              showFrag1= (EditText) view.findViewById(R.id.edtText);
                              Bundle bundle=getArguments();
                              String a=getArguments().getString("hello");//Use This or The Below Commented Code
                              showFrag1.setText(a);
                              //showFrag1.setText(String.valueOf(bundle.getString("hello")));
                              return view;
                          }
                      }
          I used Frame Layout easy to use.
          Don't Forget to Add Background color or else fragment will overlap.
      This is for First Fragment.
          <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:id="@+id/activity_main"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:paddingBottom="@dimen/activity_vertical_margin"
              android:paddingLeft="@dimen/activity_horizontal_margin"
              android:paddingRight="@dimen/activity_horizontal_margin"
              android:paddingTop="@dimen/activity_vertical_margin"
              android:background="@color/colorPrimary"
              tools:context="com.example.sumedh.fragmentpractice1.MainActivity">
      
              <EditText
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  android:id="@+id/editText" />
              <Button
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  android:layout_gravity="center"
                  android:id="@+id/BtnNext"/>
          </FrameLayout>
      
      
      Xml for Next Fragment.
      <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical" android:layout_width="match_parent"
         android:background="@color/colorAccent"
          android:layout_height="match_parent">
          <EditText
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:id="@+id/edtText"/>
      
      </LinearLayout>
      

      【讨论】:

      • 解释你的答案?没有任何解释的代码不会有太大帮助
      • 我已经在流程中编写了代码,以便可以理解......使用捆绑将数据从主活动传递到 FragClass1。
      【解决方案9】:

      来自活动类:

      使用捆绑参数将数据发送到片段并加载片段

         Fragment fragment = new myFragment();
         Bundle bundle = new Bundle();
         bundle.putString("pName", personName);
         bundle.putString("pEmail", personEmail);
         bundle.putString("pId", personId);
         fragment.setArguments(bundle);
      
         getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                          fragment).commit();
      

      来自 myFragment 类:

      从包中获取参数并将它们设置为 xml

          Bundle arguments = getArguments();
          String personName = arguments.getString("pName");
          String personEmail = arguments.getString("pEmail");
          String personId = arguments.getString("pId");
      
          nameTV = v.findViewById(R.id.name);
          emailTV = v.findViewById(R.id.email);
          idTV = v.findViewById(R.id.id);
      
          nameTV.setText("Name: "+ personName);
          emailTV.setText("Email: "+ personEmail);
          idTV.setText("ID: "+ personId);
      

      【讨论】:

      • 请再看一遍问题,它是关于片段到片段的
      【解决方案10】:

      如果您使用的是 kotlin,那么您可以将 bundle 传递为

      val fragment = YourFragment()
      val bundle = Bundle().apply {
          putInt("someInt", 5)
          putString("someString", "Hello")
      }
      fragment.arguments = bundle
      

      并在YourFragmentonCreate中获取这些值

      this.arguments?.let {
          val someInt    = it.getInt("someInt", someDefaultInt)
          val someString = it.getString("someString", someDefaultString)
      }
      

      【讨论】:

        【解决方案11】:

        你的输入片段

        public class SecondFragment extends Fragment  {
        
        
            EditText etext;
            Button btn;
            String etex;
            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
                View v = inflater.inflate(R.layout.secondfragment, container, false);
                etext = (EditText) v.findViewById(R.id.editText4);
                btn = (Button) v.findViewById(R.id.button);
                btn.setOnClickListener(mClickListener);
                return v;
            }
        
            View.OnClickListener mClickListener = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
        
        
                    etex = etext.getText().toString();
                    FragmentTransaction transection = getFragmentManager().beginTransaction();
                    Viewfragment mfragment = new Viewfragment();
                    //using Bundle to send data
                    Bundle bundle = new Bundle();
                    bundle.putString("textbox", etex);
                    mfragment.setArguments(bundle); //data being send to SecondFragment
                    transection.replace(R.id.frame, mfragment);
                    transection.isAddToBackStackAllowed();
                    transection.addToBackStack(null);
                    transection.commit();
        
                }
            };
        
        
        
        }
        

        你的视图片段

        public class Viewfragment extends Fragment {
        
            TextView txtv;
            public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
                View v = inflater.inflate(R.layout.viewfrag,container,false);
                txtv = (TextView)  v.findViewById(R.id.textView4);
                Bundle bundle=getArguments();
                txtv.setText(String.valueOf(bundle.getString("textbox")));
                return v;
            }
        
        
        }
        

        【讨论】:

          猜你喜欢
          • 2021-02-19
          • 2014-08-24
          • 2019-10-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-11-16
          相关资源
          最近更新 更多