I would like to reduce the following lines of code. It shouldn't be necessary to declare the class and then create an instance of it to get the run method to run. It should be possible to write the code such that you can define the class and create an instance of it as one construct. I still need the runOnUiThread to actually run it but I am looking for a condensed way to combine the class definition and instantiation. I've seen it done somewhere but can't recall how it's done:
class OnRunnableCompleted implements Runnable
{
@Override
public void run()
{
}
}
OnRunnableCompleted onRunnableCompleted = new OnRunnableCompleted();
runOnUiThread(onRunnableCompleted);
runOnUiThread(new Runnable() { public void run() {} });
This creates an anonymous class that implements the Runnable
interface and overrides the abstract run()
method to be a no-op.
The general form of an anonymous class is
new Name(superCtorParam0, superCtorParam1) {
member0;
member1;
}
where
Name
is the name of an interface or class to extend/implement,superCtorParam
0...n are parameters to Name
's constructormember
0...n are the fields, methods, initializers, inner classes of the anonymous class just like in any other class declarationHow about...
Runnable calculatePI = new Runnable(){
public void run(){/*calculate pi*/}
}
//Any time you need to calculate pi
runOnUiThread(calculatePI);
This reduces the code and prevents the repeated creation of anonymous classes. In my android development I use this solution quite often. Works well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With