Thursday, 26 September 2013

Declare a method inside an if statement and have it known to following method calls

Declare a method inside an if statement and have it known to following
method calls

I'm writing something in Android and in order to tailor for an older SDK,
I need to change what a variable becomes. I'm using ClipboardManager which
has different versions based on SDK. The issue is to create this variable
easily, I have to do it in an if, and my code won't compile after due to
the variable not being detected.
Example:
if(android.os.Build.VERSION.SDK_INT >= 11){
final android.content.ClipboardManager clipboard =
(ClipboardManager)context.getSystemService(Context.CLIPBOARD_SERVICE);
} else {
final android.text.ClipboardManager clipboard =
(ClipboardManager)context.getSystemService(Context.CLIPBOARD_SERVICE);
}
if (clipboard.hasPrimaryClip()) {
// Do stuff
}
Because the instance of clipboard depends on the SDK, if
(clipboard.hasPrimaryClip()) complains at me.
Is there any way to do this other than making two variables and checking
for null?

No comments:

Post a Comment