gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 09:06:25 24 4
gpt4 key购买 nike

在我的 FragmentActivity 中有一个 fragment 。此 fragment 从服务器加载数据。我希望我们的用户点击刷新按钮,然后我在 fragment 中调用一个方法并执行刷新过程。

我在 FragmentActivity 中创建了一个接口(interface),并在用户点击刷新按钮时设置它的变量。代码是这样的:

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 类中我实现了这个接口(interface):

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;

从其宿主访问 fragment 方法的最佳方式是什么?任何建议将不胜感激。谢谢

最佳答案

执行这个

onRefreshSelected = (OnRefreshSelected) MainScreen.this;

您正在 onRefreshSelected 字段中分配您的 Activity ,试图将其转换为您的界面,但您的 Activity 未实现该界面,这就是引发 ClassCastException 的原因。

而是使用这样的东西

    @Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_refresh:
CategoryFragment fragment = (CategoryFragment) getFragmentManager()
.findFragmentById(R.id.category_fragment);
if (fragment != null) {
fragment.getData();
}
return true;
default:
return super.onOptionsItemSelected(item);
}

您的 Activity 可以通过使用 findFragmentById() 从 FragmentManager 获取对 fragment 的引用来调用 fragment 中的方法或 findFragmentByTag() .

关于Android,如何从 FragmentActivty 重新启动/刷新 fragment ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11578000/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com