我有一个片段Movies
,可以将数据库调整为列表视图。此片段类的辅助方法之一是swapCursor
public void swapCursor(final DatabaseAdapter myAdapter, final Cursor cursor){
// Swap the cursor on the UI thread (prevents error: Only the original thread that created a view hierarchy can touch its views)
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
myAdapter.swapCursor(cursor);
}
});
}
我需要能够从外部swapCursor
类访问Movies
方法。我无法swapCursor
静态因为我无法拨打getActivity
。
如何访问swapCursor
?我是否需要获取片段类的实例并将swapCursor
作为实例方法调用?我该怎么做?
修改
我想从另一个既不是片段也不是活动类的类中调用swapCursor
,只是一个普通的Java类。我从这个方法调用的类是一个单例游标manger类。
修改
这是我的整个Movies
课程,以使事情更清晰
public class Movies extends Fragment {
static DatabaseAdapter myAdapter = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_movies, container, false);
myAdapter = new DatabaseAdapter(getActivity(), null, 0);
DatabaseHelper dbh = DatabaseHelper.getInstanceOf(getActivity());
SQLiteDatabase db = dbh.getDatabase();
String query = "SELECT 0 _id, * FROM Movies ORDER BY CAST(imdbVotes AS int) DESC";
Cursor cursor = db.rawQuery(query, null);
swapCursor(myAdapter, cursor);
ListView listView = (ListView) view.findViewById(R.id.listViewMovies);
listView.setAdapter(myAdapter);
return view;
}
public void swapCursor(final DatabaseAdapter myAdapter, final Cursor cursor){
// Swap the cursor on the UI thread (prevents error: Only the original thread that created a view hierarchy can touch its views)
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
myAdapter.swapCursor(cursor);
}
});
}
}
答案 0 :(得分:0)
如果您使用适配器进行片段(即视图寻呼机,标签适配器)//片段活动始终预先加载当前片段位置的+2。
Fragment fragment = (Fragment) pager.getAdapter().instantiateItem(pager, globalPosition);
if (((FragmentDetail) fragment).getView() != null) {
((FragmentDetail) fragment).myMethod();
}
答案 1 :(得分:0)
我通过向片段类添加两个静态全局变量来解决这个问题
static DatabaseAdapter myAdapter = null;
static Activity activity = null;
在我的onCreateView
查看方法中,我添加了以下行
activity = getActivity();
然后我将swapCursor
设为静态并删除myAdapter
参数
public static void swapCursor(final Cursor cursor){
// Swap the cursor on the UI thread (prevents error: Only the original thread that created a view hierarchy can touch its views)
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
myAdapter.swapCursor(cursor);
}
});
}
现在我可以从任何其他类中替换我的适配器中的光标=)