2017-08-07 43 views
0

我有问题在Fragment中获得的Bundle以上。如何获得不止一个包中的一个片段

用我的代码,我从活动传递数据,但没有获取片段中的值数据。

ACTIVITY:

Bundle bundle = new Bundle(); 
bundle.putIntegerArrayList("oki", hm); 
bundle.putIntegerArrayList("okiquantitapizze", hm_quantitàpizze); 

System.out.println("PERO:" + bundle); 

MyListFragment myFragment = new MyListFragment(); 
myFragment.setArguments(bundle); 
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); 
transaction.replace(R.id.a, myFragment); 
transaction.commit(); 

FRAGMENT:

try { 
    bundle = getArguments(); 

    System.out.println("BUNDLES1:" + bundle); 
    if (bundle != null) { 
     strtext = bundle.getIntegerArrayList("oki"); 
     quantitàpizze=bundle2.getIntegerArrayList("okiquantitapizze"); 

     System.out.println("CAZZ:" + strtext); 

     System.out.println("PRESO:" + quantitàpizze); 
    } 
} catch(Exception e){ 

} 
+4

什么是'bundle2'? – nikis

+0

你试图获得参数的哪个片段的方法? – artemiygreg

+0

@nikis是的,bundle2是问题.... – androidiano

回答

0

,关于如何通过一个以上的束的问题是把第二Bundle到第一。为了做到这一点,您可以使用Bundle#putAll方法:

将给定包中的所有映射插入此包中。

例如,

Bundle bundle = new Bundle(); 
Bundle bundle2 = new Bundle(); 
bundle.putAll(bundle2); // empty fields, but that's how it works 

因此,您可以访问Fragment中的每个字段。在你的情况应该是这样的

strtext = bundle.getIntegerArrayList("oki"); 
quantitàpizze=bundle.getIntegerArrayList("okiquantitapizze"); // removed bundle2 

putAlldocs

+0

只是好奇你为什么不会只使用'''Bundle#getBundle'''?否则,你将不得不处理捆绑中的每个对象,而不是捆绑本身 –

+0

@SaikCaskey通过使用'putBundle',你可以在碎片内部多一次调用以获得值。活动之间它是更好的方法,但对于碎片,通常不会,因为您希望让父Activity执行导航处理。 –

+0

但是,简单地说,通过使用putAll,您可能必须管理更多变量 - 我个人更喜欢使用捆绑结构,然后您可以对捆绑包#keySet进行foreach处理,然后处理每个事物,而不必将每个值分配给变种显然,无论哪种方式都非常有效,我只是好奇而已 –

0

虽然这是不完全的回答这个问题,但你可以使用这种方法用于片段

设置参数

可以使用newInstance方法在你的片段

public static MyListFragment newInstance(ArrayList<Integer> hm,ArrayList<Integer> hm_quantitàpizze) { 

     Bundle bundle= new Bundle(); 
     bundle.putIntegerArrayList("oki", hm); 
     bundle.putIntegerArrayList("okiquantitapizze", hm_quantitàpizze); 
     MyListFragment fragment = new MyListFragment(); 
     fragment.setArguments(bundle); 
     return fragment; 
    } 

,并得到束在onCreateView()您的片段

在活动

制作片段交易如下

MyListFragment myListFragment = MyListFragment.newInstance(hm,hm_quantitàpizze); 
    FragmentManager fragmentManager = getFragmentManager(); 
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 
fragmentTransaction.replace(R.id.frag_container,myListFragment).commit();