gpt4 book ai didi

android - 将 ArrayList> 传递给 fragment

转载 作者:搜寻专家 更新时间:2023-11-01 08:08:46 24 4
gpt4 key购买 nike

我有 3 个 ArrayList> 我想传递给 3 个 fragment 。除了将它们设为静态之外,最好的方法是什么?

最佳答案

您可以在 Fragment 中使用 setArguments。看看http://developer.android.com/guide/components/fragments.html ,基本上,您在创建 fragment 之前创建一个 Bundle,然后将其设置为一个参数。

Android 文档中的示例:

public static class DetailsActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

if (getResources().getConfiguration().orientation
== Configuration.ORIENTATION_LANDSCAPE) {
// If the screen is now in landscape mode, we can show the
// dialog in-line with the list so we don't need this activity.
finish();
return;
}

if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
DetailsFragment details = new DetailsFragment();
details.setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction().add(android.R.id.content, details).commit();
}
}
}

不是使用 getIntent().getExtras(),而是创建 bundle 并设置参数

Bundle bundle = new Bundle();
bundle.putSerializable(YOUR_KEY, yourObject);
fragment.setArguments(bundle);

对于您的 fragment :

public static class DetailsFragment extends Fragment {
/**
* Create a new instance of DetailsFragment, initialized to
* show the text at 'index'.
*/
public static DetailsFragment newInstance(int index) {
DetailsFragment f = new DetailsFragment();

// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);

return f;
}

public int getShownIndex() {
return getArguments().getInt("index", 0);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
// We have different layouts, and in one of them this
// fragment's containing frame doesn't exist. The fragment
// may still be created from its saved state, but there is
// no reason to try to create its view hierarchy because it
// won't be displayed. Note this is not needed -- we could
// just run the code below, where we would create and return
// the view hierarchy; it would just never be used.
return null;
}

ScrollView scroller = new ScrollView(getActivity());
TextView text = new TextView(getActivity());
int padding = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
4, getActivity().getResources().getDisplayMetrics());
text.setPadding(padding, padding, padding, padding);
scroller.addView(text);
text.setText(Shakespeare.DIALOGUE[getShownIndex()]);
return scroller;
}
}

关于android - 将 ArrayList<HashMap<String, String>> 传递给 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11884971/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com