通过bundle在片段之间传递值

时间:2018-06-08 11:37:36

标签: java android

我是初学者,是Android技术的新手。其实我试图通过不同的方法解决已存在的问题。我在单个活动中获取了3个片段,在第一个片段中我使用了editText,在第二个片段中我拿了按钮,点击该按钮后我试图在第3个片段中显示fragment1数据通过Bundle传递值并且我卡住了。如何通过这种方法完成这项任务。

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;
    }
}

2 个答案:

答案 0 :(得分:0)

在设置args之前,您需要更改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();

}

获取片段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");

这是空的,这就是为什么解决方案是你不需要将Top片段值传递给Mid Fragment只需编辑文本make static就像这样

更改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;
}

}

答案 1 :(得分:0)

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

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");
}