在Android中使用片段,标签和列表

时间:2017-01-23 06:46:31

标签: java android android-fragments

我在活动中有一个项目的ArrayList,当我点击不同的标签时,我想重新排列和查看。我为每个选项卡创建了片段,我已经有了重新排列方法。我不知道如何从活动中访问Collection并将其传递到片段中进行排列。最好的方法是什么;

3 个答案:

答案 0 :(得分:1)

在“活动”中,创建一个返回Collection对象的方法。 e.g

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

并在你的片段使用方法

(TypeCast_to_your_Activity)getActivity().getCollection();

答案 1 :(得分: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
    }
}

答案 2 :(得分:0)

您应该使用从FragmentStatePagerAdapter扩展的自定义适配器来保存数据的视图寻呼机。在Custom适配器中,将数据传递给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()中,你可以将传递的数据作为Arguments获取,并按预期使用它。