简体   繁体   中英

Type-Casting a java object according to Android SDK Level

I fill a list with checkBoxPreference objects programmatically. For new android SDK, there's a method setIcon() that was not implemented before.

So I extended the checkBoxPreference class and implemented the setIcon() similar to this gist . My new class is called IconCheckBoxPreference, which has issues with 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. What could by the type of "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.

As for the casting, use CheckboxPreference as the common superclass object type, so you can still call setTitle() independently of the platform version.

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

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