
[英]How can I retrieve an instance of my fragment class so I can call a method on it?
[英]How to call an instance method on a fragment class?
我有一个片段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);
}
});
}
我需要能够从Movies
类外部访问swapCursor
方法。 我无法使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);
}
});
}
}
如果您正在使用适配器进行片段(即视图寻呼机,选项卡适配器)//片段活动始终预先加载+2当前片段位置。
Fragment fragment = (Fragment) pager.getAdapter().instantiateItem(pager, globalPosition);
if (((FragmentDetail) fragment).getView() != null) {
((FragmentDetail) fragment).myMethod();
}
我通过向片段类添加两个静态全局变量来解决这个问题
static DatabaseAdapter myAdapter = null;
static Activity activity = null;
在我的onCreateView
视图方法中,我添加了以下行
activity = getActivity();
然后我将swapCursor
static并删除了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);
}
});
}
现在我可以从任何其他类交换我的适配器中的光标=)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.