简体   繁体   English

根据Android SDK级别键入Java对象

[英]Type-Casting a java object according to Android SDK Level

I fill a list with checkBoxPreference objects programmatically. 我以编程方式用checkBoxPreference对象填充列表。 For new android SDK, there's a method setIcon() that was not implemented before. 对于新的android SDK,有一个方法setIcon()以前没有实现。

So I extended the checkBoxPreference class and implemented the setIcon() similar to this gist . 因此,我扩展了checkBoxPreference类并实现了类似于this gist的setIcon()。 My new class is called IconCheckBoxPreference, which has issues with Kitkat [new SDK]. 我的新类称为IconCheckBoxPreference,它与Kitkat [new SDK]有关。

I want to have something like 我想要类似的东西

Object cbp;
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB){
    cbp        = new checkBoxPreference(this);
    casted_cbp = CastAccordingToClass(cbp, checkBoxPreference.class); //TODO!
}else{
    cbp = new IconCheckBoxPreference(this, null);
    casted_cbp = CastAccordingToClass(cbp, IconCheckBoxPreference.class); //TODO!
}
casted_cbp.setTitle("My Title");
casted_cbp.setIcon(getResources().getDrawable(R.drawable.bla));

And continue my code using the variable "casted_cbp" without further SDK conditions. 并使用变量“ casted_cbp”继续执行我的代码,而无需其他SDK条件。 What could by the type of "casted_cbp"? “ casted_cbp”的类型可能是什么? Is there a way for doing so? 有办法吗? What's the best practice in such situations? 在这种情况下,最佳做法是什么?

What you want is not possible. 您想要的是不可能的。

You will have to set the icon in the if, when the compiler still knows the exact concrete class. 当编译器仍然知道确切的具体类时,您将必须在if中设置图标。

As for the casting, use CheckboxPreference as the common superclass object type, so you can still call setTitle() independently of the platform version. 至于强制转换,请使用CheckboxPreference作为常见的超类对象类型,因此您仍然可以独立于平台版本调用setTitle()

This is what the code will look like: 代码如下所示:

CheckBoxPreference cbp; 
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB){
    CheckBoxPreference pref = new checkBoxPreference(this); 
    pref.setIcon(getResources().getDrawable(R.drawable.bla));
    cbp = pref;
}else{ 
    IconCheckBoxPreference pref = new IconCheckBoxPreference(this, null); 
    pref.setIcon(getResources().getDrawable(R.drawable.bla));
    cbp = pref;
}
cbp.setTitle("My Title");

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

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