在我的 FragmentActivity 我有一个片段。该片段从服务器加载数据。我希望我们用户单击刷新按钮,然后我在片段中调用一个方法并执行刷新过程。
我在 FragmentActivity 中创建了一个界面,并在用户单击刷新按钮时设置其变量。代码是这样的:
public class MainScreen extends FragmentActivity {
public interface OnRefreshSelected {
public void refreshFragment(boolean flag);
}
private OnRefreshSelected onRefreshSelected;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "Try to create MainScreen...");
setContentView(R.layout.activity_main);
onRefreshSelected = (OnRefreshSelected) MainScreen.this;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_refresh:
onRefreshSelected.refreshFragment(true);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
在 Fragment 类中我实现了这个接口:
public class CategoryFragment extends Fragment implements OnRefreshSelected {
@Override
public void refreshFragment(boolean flag) {
Log.i(TAG, "refresh requested. Try to reload data for this fragment...");
getData();
}
}
当我运行时,应用程序崩溃并且 logcat 显示以下消息:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.astro.recipe.activities/com.astro.recipe.activities.MainScreen}: java.lang.ClassCastException: com.astro.recipe.activities.MainScreen
并指向这一行:
onRefreshSelected = (OnRefreshSelected) MainScreen.this;
从宿主访问片段方法的最佳方法是什么?任何建议将不胜感激。谢谢