Reputation: 974
In the accepted answer of the following post(Android custom numeric keyboard) I found a syntax that I don't understand:
$(R.id.t9_key_0).setOnClickListener(this);
What does the dollar sign mean in front? Is it specifically related to Android resource ids or is more a general Java syntax? Search engine results didn't show any suitable results.
Upvotes: 33
Views: 2891
Reputation: 58934
Earlier days we know we needed to cast every return type of findViewById()
method. Like
usual way
TextView textView = (TextView) findViewById(R.id.textView);
This guy way
TextView textView = $(R.id.textView);
He ignored typecasting by his generic method.
So the guy used Java generic to ignore type casting all the findViewById();
. If you don't understand Generics, please read Why to use generics.
protected <T extends View> T $(@IdRes int id) {
return (T) super.findViewById(id);
}
So now he doesn't need to type cast
TextView textView = $(R.id.textView);
Explanation of this method.
@IdRes
so that Android Studio only allow resource ids in this parameter.findViewById
which returns View.<T extends View>
from method, so you will always have View object in return type.Now you don't need to make your generic methods. Because Android itself has changed his method. See Android Oreo Changes for findViewById()
.
All instances of the findViewById() method now return T instead of View.
Now you also can do same like that guy without typecasting
TextView textView = findViewById(R.id.textView);
Upvotes: 1
Reputation: 152787
It's a method call where the method name is $
. The method is defined as follows in the code you linked:
protected <T extends View> T $(@IdRes int id) {
return (T) super.findViewById(id);
}
The method is a helper that removes the need to cast the return type of findViewById()
. It's no longer needed as of Android O as the platform findViewById()
uses generics to do the same.
The name $
is likely inspired by jQuery.
Upvotes: 40