Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Universal method for adding fragment, how to implement it

I'm trying to create method for fragment's adding, that i will be able to use many times, but i've faced some error. This is my method:

// global variable
fragManager = getSupportFragmentManager();
private <T> void findFragmentByTagAndAdd(String fragmentTag, Class<?> cls, T t){
    Fragment fragm = fragManager.findFragmentByTag(fragmentTag);
    if (fragm == null) {
        fragm = cls.newInstance(t);
        fragManager.beginTransaction()
                .add(R.id.host_fragment_container, fragm)
                .commit();
    } 
}

Where T t is some data (for example some model class) that must be passed to setArguments of fragment's newInstance method

I get next error :

    cannot be applied to given types;
                    fragm = cls.newInstance(t);
                               ^   required: no arguments   
found: T#1   reason: actual and formal argument lists differ in length
like image 461
Stanly T Avatar asked Nov 26 '25 18:11

Stanly T


1 Answers

Replace this:

fragm = cls.newInstance(t);

with something like:

Constructor constructor = cls.getConstructor(t.getClass());
fragm = (Fragment) constructor.newInstance(t);
like image 151
Benoit Avatar answered Nov 29 '25 11:11

Benoit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!