实际上,我知道如何将额外的值从一个活动发送到另一个片段,但我需要将联系人游标发送到片段,然后将该游标传递给游标适配器,并在listview中显示数据。
发布于 2014-01-09 06:16:20
使用构造函数获取片段的值。然后将值从构造函数分配给实例变量。然后,您可以在onCreateView()方法中使用游标来启动片段来初始化它。
Updated:创建setter方法,用于在片段中设置游标,因此添加以下方法
public static setMyCursor(Cursor pCursor){
this.cursor=pCursor;
}将构造函数用作公共
public MyFragment(){
}使用setMyCursor()方法设置游标
发布于 2014-01-09 06:57:04
有很多方法来完成你想要做的事情。只有其中一些要求您在创建片段之前拥有游标。
您可以创建一个创建片段并传入游标的方法:
public class YourFragment extends Fragment {
private Cursor mCursor;
public static YourFragment createYourFragmentWithCursor( Cursor cursor ) {
YourFragment fragment = new YourFragment();
fragment.setCursor( cursor );
return fragment;
}
@Override
public void onViewCreated (View view, Bundle savedInstanceState) {
ListView listView = (ListView) findViewById( R.id.yourListView );
listView.setAdapter( new CursorAdapter( getActivity(), getCursor() );
}
protected Cursor getCursor() {
return mCursor;
}
private Cursor setCursor( Cursor cursor ) {
mCursor = cursor;
}
}您可以将游标从活动传递到它控制的片段,以便让活动实现一个包含返回游标的方法的接口。然后,在您的片段中,您可以获得对该接口的引用。
例如:
public interface CursorProvidingInterface {
Cursor getCursor();
}
public class YourActivity extends Activity implements CursorProvidingInterface {
...
@Override
public Cursor getCursor() {
Cursor cursor = whateverYouDoToAcquireYourCursor();
return cursor;
}
...
}
public class YourFragment extends Fragment {
private CursorProvidingInterface cursorProvidingInterface;
@Override
public void onAttach( Activity activity ) {
try {
cursorProvidingInterface = (CursorProvidingInterface) activity;
}
catch (ClassCastException e) {
throw new RuntimeException( activity.getClass().getName() + " must implement " + CursorProvidingInterface.class.getName() );
}
}
@Override
public void onViewCreated (View view, Bundle savedInstanceState) {
ListView listView = (ListView) findViewById( R.id.yourListView );
listView.setAdapter( new CursorAdapter( getActivity(), cursorProvidingInterface.getCursor() );
}
}根据你的情况,上述策略可能不是最好的选择。
假设您的游标来自数据库,我建议您在创建片段时从数据库中获取游标。如果有必要,可以将所需的任何查询参数作为参数传递给片段。
在这种情况下,我更喜欢使用某种形式的依赖注入(如RoboGuice ),并创建一个@Singleton类来处理数据库事务,然后您可以@ injection,然后在需要时调用它。
您可以考虑实现ContentProvider并使用它获取所需的游标。如果您从光标显示的数据可能经常发生更改,则这可能特别有用。
最后两种情况是在游标中传递数据的更健壮的方法,我建议您熟悉它们。对这些方法的教程的搜索将产生比我在这里提供的更好的示例。
https://stackoverflow.com/questions/21012758
复制相似问题