[英]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
,只有當object
是FirstSonClass
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.