gpt4 book ai didi

java - 如何编写一个以 fragment 类作为参数的方法,该方法将允许我创建该 fragment 的新实例?

转载 作者:行者123 更新时间:2023-12-01 18:44:18 24 4
gpt4 key购买 nike

目标

我正在尝试编写一种方法来替换我用来交换 fragment 的代码,以便将复制和发布保持在最低限度(并保持 D.R.Y.)

问题

当我尝试使用作为参数传入的类来创建该类的新实例时,出现错误。

错误发生在这行代码中,位于运算符(等号)左侧:

newFragmentClass new_fragment = newFragmentClass.newInstance();     

它给我的错误是:“newFragmentClass 无法解析为类型”。

完整代码
    private void changeFragment(Class<?> newFragmentClass)
{
// Detect the current fragment
Fragment current_fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container);

// Create a new instance of the given class, edit later to gracefully handle errors
newFragmentClass new_fragment = newFragmentClass.newInstance();

// Switch to the new fragment
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.detach(current_fragment);
transaction.replace(R.id.fragment_container, new_fragment);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.commit();

// Change the tab background to indicate that the tab is active, reset backgrounds for any other tabs
findViewById(R.id.page_one_tab).setBackgroundResource(R.drawable.menu_button_background_active);
findViewById(R.id.page_two_tab).setBackgroundResource(R.drawable.menu_button_background);
findViewById(R.id.page_three_tab).setBackgroundResource(R.drawable.menu_button_background);

}

// Page One Tab Button Functionality
public void pageOneTab (View v)
{
// Change the fragment to SelectPlayersFragment
changeFragment(Page_One_Fragment.class);
}
尝试的解决方案

我已经在 StackOverflow 和整个互联网上搜索了一段时间,但未能找到解决方案。几个主题like this one似乎他们会解决问题,但后来我在 transaction.replace 行上遇到了一个错误,我找不到修复程序:“FragmentTransaction 类型中的方法 Replace(int, Fragment) 不适用于参数(整数,对象)”。

最佳答案

也许更简单的解决方案是将 Fragment 作为参数传递,而不是 Class,并使用它来替换当前 fragment 。此外,您不需要分离当前 fragment ,这就是 replace() 为您所做的事情。

类似这样的事情:

public void changeFragment(Fragment fragment) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fragment_container, fragment, "tag");
transaction.commit();
//.....
}

你可以像这样使用它:

changeFragment(new Page_One_Fragment());

关于java - 如何编写一个以 fragment 类作为参数的方法,该方法将允许我创建该 fragment 的新实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18505017/

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