我有 3 个 ArrayList> 我想传递给 3 个片段。除了使它们静态之外,最好的方法是什么?
问问题
4402 次
2 回答
3
您可以在片段中使用 setArguments。看看http://developer.android.com/guide/components/fragments.html,基本上,您在创建 Fragment 之前创建一个 Bundle,然后将其设置为 Argument。
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 = new Bundle();
bundle.putSerializable(YOUR_KEY, yourObject);
fragment.setArguments(bundle);
对于你的片段:
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;
}
}
于 2012-08-09T14:04:20.393 回答
1
您可以创建侦听器回调接口并在您的片段中实现它们。像这样的东西:
@Override
public void onSomeEvent(List<SomeData> data) {
//do something with data
}
在您的活动中创建此界面:
public interface OnSomeEventListener {
onSomeEvent(List<SomeData> data);
}
然后使用 findFragmentById 或 findFragmentByTag 获取您的片段并将其分配给侦听器:
this.onSomeEventListener = fragment;
然后您可以调用该接口的方法,您的片段将接收回调。
片段和活动之间的第二种更简单的通信方式是广播接收器。您可以在片段中注册一些广播接收器,然后从活动中调用 sendBroadcast()。您的数据列表可以放在该广播消息的捆绑中。
于 2012-08-09T14:22:38.397 回答