简体   繁体   中英

pass Class name as attribute XML in Android

I have classes which extend one class

public abstract class FatherClass{
    int num;
    FatherClass(int num){
        this.num= num;
    }   
}

public class FirstSonClass extend FatherClass{
    FirstSonClass(int num){
        super(num)
    }
}

public class SecondSonClass extend FatherClass{
    SecondSonClass(int num){
        super(num)
    }
}

when my program starts it should create an static instance of one of the sons.

public class MainActivity {
    public Static FatherClass STATIC_SON;

    @override
    protected void onCreate(Bundle savedInstance){
        super.onCreate(savedInstanceState);
        setTheme(R.style.AppTheme);
        setContentView(R.layout.activity_main);
        
        // I got this condition from external 
        if(loadExternalCondition()){
            STATIC_SON = new FirstSonClass(4);
        }else {
            STATIC_SON = new SecondSonClass(43);
    }

}

Now in one Fragment I have an customView and I want to show this customView only if the object is instance of FirstSonClass . I don't know which format should the type got. I am thinking to make it string and pass it here. and in CustomView class maybe in some way I can generate a class name.

<LinearLayout

    <com.whatEver.CustomView
        android:id="@+id/first_view"
        app:type="FirstSonClass"

    </com.whatEver.CustomView>


    <com.whatEver.CustomView
        android:id="@+id/second_view"
        app:type="SecondSonClass"

    </com.whatEver.CustomView>
</LinearLayout>

Now I just want that customView decide to show itself depending on the static class, and the passed class, if the both instanced from the same class then it should shows itself, otherwise hide itself.

public CustomView(context, AttributeSet attrs){
     super(context,attrs);
     init(context,attrs);
}

private init(context, AttributeSet attrs){
     TypedArray typedArray = context.obtainStyledAttributes(atrrs, R.styleable.CustomView);
    try {
         FatherClass father =typedArray.getClass(R.styleable,CustomView_type);
        }
    } finally {
        typedArray.recycle();
    }    

    if(MainActivity.STATIC_SON instanceOf father){
       this.show()
    }else {
       this.hide()
    }
}

my aim is:

When STATIC_SON is instanceOf FirstSonClass then show firstView . And When is instanceOf SecondSonClass show secondView otherwise don't show anything.

No need to create instance to check types, object instanceOf class

private init(context, AttributeSet attrs){
    if(MainActivity.STATIC_SON instanceOf FirstSonClass){
       this.show()
    }else {
       this.hide()
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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