当前位置: 首页 > 工具软件 > Android Astro > 使用案例 >

android重新启动fragment,Android,如何从FragmentActivty重新启动/刷新片段?

艾修筠
2023-12-01

在我的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;

从主机访问片段方法的最佳方法是什么?

任何建议将不胜感激.谢谢

 类似资料: