[英]pass Class name as attribute XML in Android
I have classes which extend one class我有扩展一个 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.当我的程序启动时,它应该创建一个儿子的 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);
}
}
Now in one Fragment
I have an customView
and I want to show this customView
only if the object
is instance of FirstSonClass
.现在在一个Fragment
中,我有一个customView
,只有当object
是FirstSonClass
customView
I don't know which format should the type
got.我不知道该type
应该采用哪种格式。 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.在 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. 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
.当STATIC_SON
是 instanceOf FirstSonClass
然后显示firstView
。 And When is instanceOf SecondSonClass
show secondView
otherwise don't show anything.并且 instanceOf SecondSonClass
显示secondView
否则不显示任何内容。
No need to create instance to check types, object instanceOf class
无需创建实例来检查类型, 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.