繁体   English   中英

通过 Class 名称作为属性 XML 在 Android

[英]pass Class name as attribute XML in Android

我有扩展一个 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)
    }
}

当我的程序启动时,它应该创建一个儿子的 static 实例。

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);
    }

}

现在在一个Fragment中,我有一个customView ,只有当objectFirstSonClass customView 我不知道该type应该采用哪种格式。 我想把它串起来并在这里传递。 在 CustomView class 中,也许我可以以某种方式生成 class 名称。

<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()
    }
}

我的目标是:

STATIC_SON是 instanceOf FirstSonClass然后显示firstView 并且 instanceOf SecondSonClass显示secondView否则不显示任何内容。

无需创建实例来检查类型, object instanceOf class

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

暂无
暂无

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

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