【问题标题】:Passing values among fragments through bundle通过捆绑在片段之间传递值
【发布时间】:2018-06-08 11:37:36
【问题描述】:

我是一个初学者,刚接触 Android 技术。实际上我试图通过不同的方法解决已经存在的问题。我在单个活动中采用了 3 个片段,在第一个片段中我采用了 editText,在第二个片段中我采用了按钮,然后单击该按钮后,我尝试通过通过 Bundle 传递值来在第三个片段中显示 fragment1 数据,但我被卡住了。如何通过这种方法完成这项任务。

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

    <FrameLayout
        android:id="@+id/top"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:layout_weight="1"
        >
    </FrameLayout>

    <FrameLayout
        android:id="@+id/mid"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:layout_weight="1"
        >
    </FrameLayout>

    <FrameLayout
        android:id="@+id/bottom"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:layout_weight="1"
        >
    </FrameLayout>
</LinearLayout>

MainActivity

package com.example.com.dynamicfragmentproject;
import android.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

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

        android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        Top_fragment frg1=new Top_fragment();
        transaction.add(R.id.top,frg1);
        transaction.commit();

    }

    public void cacheData(String str) {

        android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        Mid_fragment frg2=new Mid_fragment();
        transaction.add(R.id.mid,frg2);
        transaction.commit();


        Bundle bundle = new Bundle();
        bundle.putString("editText",str);
        frg2.setArguments(bundle);
    }

    public void cacheData1(String name) {


        android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        Bottom_fragment frg3=new Bottom_fragment();
        transaction.add(R.id.bottom,frg3);
        transaction.commit();


        Bundle bundle = new Bundle();
        bundle.putString("editText",name);
        frg3.setArguments(bundle);
    }
}

fragment1.xml

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

<!-- TODO: Update blank fragment layout -->
<EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:hint="@string/hello_blank_fragment"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:textColor="@color/colorPrimary"/>

</RelativeLayout>

Fragment1.java

package com.example.com.dynamicfragmentproject;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

public class Top_fragment extends Fragment {

    private EditText editText;
    View view;

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                            Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_top_fragment, container, false);

        editText = view.findViewById(R.id.editText1);
        String str = editText.getText().toString();
        MainActivity main = (MainActivity) getActivity();

        main.cacheData(str);

        return view;
    }
}

fragment2.xml

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


   <Button
   android:id="@+id/button1"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:layout_marginLeft="25dp"
   android:layout_marginRight="25dp"
   android:text="Submit"
   android:textAllCaps="false"
   android:textColor="@color/colorPrimary"
   android:layout_centerVertical="true"
   android:layout_centerHorizontal="false"
   />

</RelativeLayout>

Fragment2.java

package com.example.com.dynamicfragmentproject;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

public class Mid_fragment extends Fragment {

    private Button buttonSubmit;
    View view;

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


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

        view = inflater.inflate(R.layout.fragment_mid_fragment, container, false);

        buttonSubmit = view.findViewById(R.id.button1);

        buttonSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                MainActivity main1 = (MainActivity) getActivity();

                Bundle bundle = getArguments();
                String name = bundle.getString("editText");

                main1.cacheData1(name);
            }
        });
        return view;
    }
}

fragment3.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"
android:id="@+id/bottom"
tools:context=".Bottom_fragment">

<!-- TODO: Update blank fragment layout -->
<TextView
    android:id="@+id/textView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/colorPrimary"
    android:padding="10dp"
     />
</FrameLayout>

Fragment3.java

package com.example.com.dynamicfragmentproject;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

public class Bottom_fragment extends Fragment {

    private TextView viewText;
    View view;

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

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


        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_bottom_fragment, container, false);

        viewText = view.findViewById(R.id.textView1);

        Bundle bundle = getArguments();
        String name = bundle.getString("editText");
        viewText.setText(name);

        return view;
    }
}

【问题讨论】:

  • 通读this
  • 检查更新是否有专业人士告知

标签: java android


【解决方案1】:

在第一个片段中创建第二个片段的对象。

FragmentTwo fragmenttwo=new FragementTwo();
Bundle bundle = new Bundle();
bundle.putSerializable(object,"data")
fragmenttwo.setArguments(bundle);

在第二个片段中

Bundle bundle = getArguments();
if(bundle != null){
   SampleModel model = (SampleModel) bundle.getSerializable("data");
}

【讨论】:

    【解决方案2】:

    你需要在设置参数之前更改MainActivity中的代码,你commit()。在整个应用程序中更改代码,如下所示

    public void cacheData(String str) {
    
        android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        Mid_fragment frg2=new Mid_fragment();
    
        Bundle bundle = new Bundle();
        bundle.putString("editText",str);
        frg2.setArguments(bundle);
    
        transaction.add(R.id.mid,frg2);
        transaction.commit();
    
    }
    

    并在 Fragment onCreateView 上获取数据:

     @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        String strtext = getArguments().getString("edttext");    
        return inflater.inflate(R.layout.fragment, container, false);
    }
    

    您只能在活动保存其状态之前(当用户离开活动时)使用 commit() 提交事务。如果您在该点之后尝试提交,则会引发异常。这是因为如果需要恢复活动,提交后的状态可能会丢失。对于丢失提交也没关系的情况,请使用 commitAllowingStateLoss()。

    更多详情可以参考this link

    更新: 在您的代码中传递捆绑值是完美的,但是当您在 Mid_fragment 中获得 editext 字符串时

    getArguments().getString("editText");
    

    这变得空了,这就是为什么解决方案是您不需要将顶部片段值传递给中间片段,只需像这样编辑文本使静态

    更改public static EditText editText

    Top_fragment extends Fragment {
    View view;
    public static EditText editText;
    
    }
    

    和Mid_fragment添加这个

    onClick(View v) {
    
            if (Top_fragment.editText!=null)
            strtext=Top_fragment.editText.getText().toString();
    

    这里是Mid_fragment的完整代码

    public class Mid_fragment extends Fragment {
    View view;
    private Button buttonSubmit;
    public Mid_fragment() {
        // Required empty public constructor
    }
    String strtext="";
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_mid_fragment, container, false);
    
    
        //strtext = getArguments().getString("editText");
    
        buttonSubmit = view.findViewById(R.id.button1);
    
        buttonSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
    
                if (Top_fragment.editText!=null)
                strtext=Top_fragment.editText.getText().toString();
    
                MainActivity main1 = (MainActivity) getActivity();
    
    
    
                main1.cacheData1(strtext);
            }
        });
        return view;
    }
    

    }

    【讨论】:

    • 我尝试了这种方法,但仍然没有得到解决方案。
    • 可以使用动态片段,因为静态片段中的片段不能超过两个。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    相关资源
    最近更新 更多