2017-01-23 80 views
-1

我有一個活動項目的ArrayList,當我點擊不同的選項卡時,我想重新排列和查看項目。我爲每個選項卡創建了片段,並且我已經有重新排列方法。我不知道如何從活動中訪問Collection,並將其傳遞到片段中進行排列。最好的辦法是什麼?在Android中使用片段,選項卡和列表

回答

0

最簡單的方法是使用Activity實現的接口和Fragment使用的接口。

public interface MyInterface{ 
    List<Object> getList(); 
} 


public class MainActivity extends AppCompatActivity implements MyInterface{ 
    @Override 
    public List<Object> getList(){ 
     return myList; 
    } 
} 


public class MyFragment extends Fragment{ 
    MyInterface myInterface; 

    @Override 
    public void onAttach(Context context){ 
     myInterface = (MyInterface) context; 
     // now you can call myInterface.getList() anywhere in your fragment 
    } 
} 
+0

。正確? – NVA

+0

@DapperArtisan正確。 –

0

您應該使用從FragmentStatePagerAdapter擴展的自定義適配器來存放數據的視圖尋呼機。裏面你定義適配器,將數據傳遞到您的片段的getItem這樣的:

`

@Override 
    public Fragment getItem(int position) { 
     YourFragment f = new YourFragment(); 
     Bundle args = new Bundle(); 
     args.putParcelable("data", filteredList); // get filteredList from list passed to adapter based on your rearrangement method 
     f.setArguments(args); 
     return f; 
    } 

`

那麼你的片段裏面,OnViewCreated(),就可以得到所傳遞的數據參數,並按預期使用它。

1

在你的Activity中,創建一個返回你的Collection對象的方法。 e.g

public ArrayList<String> getCollection() 
{ 
    return ur_Collection; 
} 

,並在您使用片段的方法

(TypeCast_to_your_Activity)getActivity().getCollection(); 
在此解決方案在活動中的GetList方法應該包含返回一個名爲myList中的變量所需的代碼
相關問題