如何将光标从android活动发送到片段



实际上我知道如何将额外的值从活动发送到片段,但我需要将联系人光标发送到片段中,然后我将光标传递到光标适配器,并在listview中显示数据。

有很多方法可以完成您想要做的事情。只有其中一些方法要求您在创建片段之前拥有Cursor。


您可以创建一个方法来创建您的片段并传入光标,然后:

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类来处理您的数据库事务,然后您可以@Inject,然后在需要时调用它。


您可以考虑实现ContentProvider并使用它来获取所需的游标。如果您在Cursor中显示的数据可能经常更改,这可能会特别有用。


最后两种情况是在Cursor中传递数据的更稳健的方法,我建议您熟悉它们。搜索这些方法的教程会得到比我在这里提供的更好的例子。

使用构造函数将值带到片段中。然后将构造函数中的值分配给实例变量。然后可以在onCreateView()方法中使用游标,通过片段启动来初始化它。

更新时间:创建setter方法来设置Fragment中的Cursor,因此添加以下方法

public static setMyCursor(Cursor pCursor){
this.cursor=pCursor;
}

使用构造函数作为公共

public MyFragment(){
}

使用setMyCursor()方法设置光标

最新更新