如何将String数组从ActivityMain传递给Fragment

时间:2017-10-24 20:07:21

标签: java android arrays string radio-button

如何从String[]

传递MainActivity
example.add(new Fragment1(new String[]{"answer 1", "answer 2", "answer 3"}));
example.add(new Fragment1(new String[]{"answer 4", "answer 5", "answer 6"}));

到此Fragment并使其动态生效(在滑动时)

public class Fragment1 extends Fragment {

    String stringValue;
    int imagesResId;
    TextView text;
    String[] rbData;

    public Fragment1() {
    }

    public Fragment1(String str, int imageView, String[] rb) {
        this.stringValue = str;
        this.imagesResId = imageView;
        this.rbData = rb;
    }

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

        View view = inflater.inflate(R.layout.fragment1, container, false);
        text = view.findViewById(R.id.textView);
        ImageView imageResId = view.findViewById(image);

        text.setText(stringValue);
        imageResId.setImageResource(imagesResId);

        return view;
    }
}

1 个答案:

答案 0 :(得分:0)

通过:

putStringArray("my_array", myArray);

要检索:

getArguments().getStringArray("my_array");

在你的片段中:

public static Fragment1 newInstance(String[] array) {
    Fragment1 fragment = new Fragment1();
    Bundle args = new Bundle();
    args.putStringArray("my_array", array);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        String[] myArray = getArguments().getStringArray("my_array");
    }
}

启动片段:

Fragment1 frag = Fragment1.newInstance(myArray);
FragmentTransaction ft = getFragmentManager().beginTransaction();
//.....