简体   繁体   English

通过类名动态实例化Fragment

[英]Instantiate Fragment dynamically by class name

I have a main activity with a menu to navigate through the page. 我的主要活动是通过菜单浏览页面。 To dynamize my code, I created my adapter with the name and the class of all of my fragments. 为了动态化代码,我使用所有片段的名称和类创建了适配器。

public class MenuItem {

    private String title;
    private Class className;
    ...
}

I have my adapter created that way : 我以这种方式创建了适配器:

    ArrayList<MenuItem> menuItems=new ArrayList<MenuItem>();

    menuItems.add(new MenuItem("Home", null, HomeFragment.class, R.drawable.ic_drawer, true));
    menuItems.add(new MenuItem("Schedule", null, ScheduleFragment.class, R.drawable.ic_drawer, false));

In my menu onClickListener, I want to directly open the page without doing any conditional statement : 在我的菜单onClickListener中,我想不做任何条件语句就直接打开页面:

private AdapterView.OnItemClickListener mItemClickListener = new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Class c =  ((MenuItem) mMenuAdapter.getItem(position)).getClassName();
        Fragment fragment = ??? //How do I create a Fragment dynamically ? 

        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.fl_container, fragment).commit();

This way of coding is used for the Activity, but it's simpler in that case because to change an activity, we're using only startActivity with the name of the activity, not its instance. 这种编码方式用于Activity,但在这种情况下更简单,因为要更改活动,我们仅使用带有活动名称的startActivity,而不使用其实例。

Do I need to use reflection ? 我需要使用反射吗?

Just invoke Class#newInstance() method: 只需调用Class#newInstance()方法即可:

Fragment fragment = c.newInstance();

Make sure you have the default constructor on your Fragment class. 确保您在Fragment类上具有默认构造函数。

You'll also need to wrap this construnction into try-catch clause, because newInstance() throws couple of exceptions - InstantiationException and IllegalArgumentException . 您还需要来包装这个construnction到的try-catch子句,因为newInstance()抛出一些例外- InstantiationExceptionIllegalArgumentException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM