I have tried many solutions found in google by the keywords: multiple constructors, scala, inheritance, subclasses.
None seems to work for this occasion. ImageView has three constructors:
ImageView(context)
ImageView(context,attribute set)
ImageView(context,attribute set, style)
In scala you can only extend one of them. And the solution of using the more complete constructor (ImageView(context,attribute set, style)) and passing default values does not work either because the constructor ImageView(context) does something completely different than the other two constructors.
Some solutions of using a trait or a companion object does not seem to work because the CustomView must be a class! I mean I am not the only one who uses this class (so I could write the scala code any way I wanted) there is also the android-sdk who uses this class and yes it must be a class.
target is to have a CustomView which extends ImageView and all of these work:
new CustomView(context)
new CustomView(context,attribute set)
new CustomView(context,attribute set, style)
Please let me know if you need any further clarification on this tricky matter!
According to Martin Odersky (the creator of Scala), that is not possible.
In http://scala-programming-language.1934581.n4.nabble.com/scala-calling-different-super-constructors-td1994456.html:
"is there a way to call different super-constructors within different
class-constructors - or does all have to go up to the main-constructor and only
one super-constructor is supported?
No, it has to go through the main constructor. That's one detail where
Scala is more restrictive than Java."
I think your best approach is to implement your views in Java.
It sounds like you may just be better off writing the subclass in Java. Otherwise, if your assumption about the SDK using the three argument constructor is correct, then you could use a trait and a class with a companion object. The SDK would use the three argument constructor of CustomView which also implements a trait containing any additional behavior you need:
trait TCustomView {
// additional behavior here
}
final class CustomView(context: Context, attributes: AttributeSet, style: Int)
extends ImageView(context, attributes, style) with TCustomView
In the application code, you could use the one, two or three argument version in this way:
object CustomView {
def apply(c: Context, a: AttributeSet, s: Int) =
new ImageView(c, a, s) with TCustomView
def apply(context: Context, attributes: AttributeSet) =
new ImageView(context, attributes) with TCustomView
def apply(context: Context) = new ImageView(context) with TCustomView
}
CustomView(context)
CustomView(context, attributes)
CustomView(context, attributes, style)
Seems like a lot of work. Depending on your goals, you might be able to add additional behavior with implicits:
implicit def imageViewToCustomView(view: ImageView) = new {
def foo = ...
}
This question lead me to several design considerations which I would like to share with you.
My first consideration is that if a Java class has been correctly designed the availability of multiple constructors should be a sign of the fact that some class properties might have default value.
Scala provides default values as a language feature, so that you do not have to bother about providing multiple constructors at all, you can simply provide default value for some arguments of your constructor. This approach leads to a much cleaner API than three different constructors which produce this kind of behaviour as you are making clear why you do not need to specify all the parameters.
My second consideration is that this is not always applicable in case you are extending classes of a third-party library. However:
if you are extending a class of an open source library and the class is correctly designed, you can simply investigate the default values of the constructor argument
if you are extending a class which is not correctly designed (i.e. where overloaded constructors are not an API to default some parameters) or where you have no access to the source, you can replace inheritance with composition and provide an implicit conversion.
class CustomView(c: Context, a: Option[AttributeSet]=None, s: Option[Int]=None){
private val underlyingView:ImageView = if(a.isDefined)
if (s.isDefined)
new ImageView(c,a.get,s.get)
else
new ImageView(c,a.get)
else
new ImageView(c)
}
object CustomView {
implicit def asImageView(customView:CustomView):ImageView = customView.underlyingView
}
According to the Android View documentation View(Context) is used when constructed from code and View(Context, AttributeSet) and View(Context, AttributeSet, int) (and since API level 21 View(Context, AttributeSet, int, int)) are used when the View is inflated from XML.
The XML constructor all just call the same constructor, the one with the most arguments which is the only one with any real implementation, so we can use default arguments in Scala. The "code constructor" on the other hand may have another implementation, so it is better to actually call in from Scala as well.
The following implementation may be a solution:
private trait MyViewTrait extends View {
// implementation
}
class MyView(context: Context, attrs: AttributeSet, defStyle: Int = 0)
extends View(context, attrs, defStyle) with MyViewTrait {}
object MyView {
def apply(context: Context) = new View(context) with MyViewTrait
}
The "code constructor" may then be used like:
var myView = MyView(context)
(not a real constructor).
And the other once like:
var myView2 = new MyView(context, attrs)
var myView3 = new MyView(context, attrs, defStyle)
which is the way the SDK expects them.
Analogously for API level 21 and higher the class can be defined as:
class MyView(context: Context, attrs: AttributeSet, defStyle: Int = 0, defStyleRes: Int = 0)
extends View(context, attrs, defStyle, defStyleRes) with MyViewTrait {}
and the forth constructor can be used like:
var myView4 = new MyView(context, attrs, defStyle, defStyleRes)
Update:
It gets a bit more complicated if you try to call a protected method in View, like setMeasuredDimension(int, int) from the trait. Java protected methods cannot be called from traits. A workaround is to implement an accessor in the class and object implementations:
private trait MyViewTrait extends View {
protected def setMeasuredDimensionAccessor(w: Int, h: Int): Unit
def callingSetMeasuredDimensionAccessor(): Unit = {
setMeasuredDimensionAccessor(1, 2)
}
}
class MyView(context: Context, attrs: AttributeSet, defStyle: Int = 0)
extends View(context, attrs, defStyle) with MyViewTrait {
override protected def setMeasuredDimensionAccessor(w: Int, h: Int) =
setMeasuredDimension(w, h)
}
object MyView {
def apply(context: Context) = new View(context) with MyViewTrait {
override protected def setMeasuredDimensionAccessor(w: Int, h: Int) =
setMeasuredDimension(w, h)
}
}
Related
We are working with 5 people on a project.
I have custom TextView component in Android project.
Some of my team friends are using Android Textview (or AppCompatTextView) directly. I want to make it mandatory to use the text view that I created as a custom TextView.
How do I do this? I look forward to your help, thank you.
While coding guidelines and code reviews should catch those issues. You could also create a custom lint check and force your builds to fail on lint errors.
Something like this:
class TextViewDetector : ResourceXmlDetector() {
override fun getApplicableElements(): Collection<String>? {
return listOf(
"android.widget.TextView", "androidx.appcompat.widget.AppCompatTextView"
)
}
override fun visitElement(context: XmlContext, element: Element) {
context.report(
ISSUE, element, context.getLocation(element),
"Do not use TextView"
)
}
companion object {
val ISSUE: Issue = Issue.create(
"id",
"Do not use TextView",
"Use custom view",
CORRECTNESS, 6, Severity.ERROR,
Implementation(TextViewDetector::class.java, RESOURCE_FILE_SCOPE)
)
}
}
There is a guide, an example repository from google and an extensive api guide on how to write custom lint checks.
You can create your own ViewInflater
class MyViewInflater {
fun createView(
parent: View?, name: String?, context: Context,
attrs: AttributeSet, inheritContext: Boolean,
readAndroidTheme: Boolean, readAppTheme: Boolean, wrapContext: Boolean
): View {
// ...
val view: View = when (name) {
"TextView",
"androidx.appcompat.widget.AppCompatTextView",
"com.google.android.material.textview.MaterialTextView" -> createMyTextView(context, attrs)
//other views
}
//...
return view
}
fun createMyTextView(context: Context, attrs: AttributeSet) = MyTextView(context, attrs)
}
and install it in your app theme
<style name="Theme.MyAppTheme" parent="Theme.SomeAppCompatParentTheme">
<item name="viewInflaterClass">package.MyViewInflater</item>
</style>
It will return your View for all tags you specify
See AppCompatViewInflater
There's no technical way to do this. The answer is coding guidelines and code reviews.
I know it's possible to use a custom view instead of a basic map marker in Google Maps doing what's described in this answer. I was curious if it was possible to achieve a similar affect with Compose?
Since ComposeView is a final class, couldn't extend that directly so I was thinking of having a FrameLayout that could add it as a child. Although this seems to be causing a race condition since composables draw slightly differently from normal android Views.
class MapMarkerView : FrameLayout {
constructor(context: Context) : super(context) {
initView()
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
initView()
}
private fun initView() {
val composeView = ComposeView(context).apply {
layoutParams = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
}
composeView.setContent {
// this runs asynchronously making the the bitmap generation not include composable at runtime?
Text(text = "2345", modifier = Modifier.background(Color.Green, RoundedCornerShape(4.dp)))
}
addView(composeView)
}
}
Most articles I have read have some callback function for generating a bitmap like this which wouldn't necessarily work in this use case where each view is generated dynamically and needed to be converted to a bitmap right away for the map.
The MapMarkerView you are attempting to create is an indirect child of ViewGroup. ComposeView is also an indirect child of ViewGroup which means you can directly substitute a ComposeView in places where you intend to use this class. The ComposeView class is not meant to be subclassed. The only thing you really need to be concerned with as a developer is its setContent method.
val composeView: View = ComposeView(context).apply{
setContent {
Text(text = "2345", modifier = Modifier.background(Color.Green, RoundedCornerShape(4.dp)))
}
}
Now you can replace the MapMarkerView with this composeView in your code or even use it at any location where a View or any of it's subclasses is required.
As we have our App on Android O, there's a new feature introduced there, where it auto-suggest Home and Work location as per image below.
What is this called? Is there a way to disable it from our Edit Text showing it?
Apparently in Android-Oreo, there's this new feature call AUTOFILL
https://developer.android.com/guide/topics/text/autofill.html, where By default, the view uses the IMPORTANT_FOR_AUTOFILL_AUTO mode, which lets Android use its heuristics to determine if the view is important for autofill
Hence for field that is not intended to have that filled, just add the below to your view.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
setImportantForAutofill(IMPORTANT_FOR_AUTOFILL_NO);
}
Update: Found another approach to disable AUTOFILL
Use android:importantForAutofill="no" in the XML
https://developer.android.com/guide/topics/text/testautofill.html#trigger_autofill_in_your_app
Accepted answer is not a solution, it doesn't work for all cases, to Disable the Autofill completely on a particular View you should extend it and override getAutofillType() method:
class TextInputEditTextNoAutofill : TextInputEditText {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
#RequiresApi(Build.VERSION_CODES.O)
override fun getAutofillType(): Int {
return View.AUTOFILL_TYPE_NONE
}
}
This is Kotlin version, but you can get the point. Showcase repo:
https://github.com/BukT0p/AutofillBug
I'm trying to make a custom ProgressBar the way I did custom layouts a lot before. This time I'm having issues.
I can achieve the desired look with just this xml:
<ProgressBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:indeterminateOnly="false"
android:progressDrawable="#drawable/progress_bar" />
The ultimate goal, however, would be doing some of the customization in the custom class so the xml shrinks to this:
<se.my.viktklubb.app.progressbar.HorizontalProgressBar
android:id="#+id/planProgressBar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
Here is the custom class:
class HorizontalProgressBar : ProgressBar {
constructor(context: Context) : super(context) {
initialSetup()
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
initialSetup()
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
initialSetup()
}
fun initialSetup() {
max = 100
isIndeterminate = false
progressDrawable = context.getDrawable(R.drawable.progress_bar)
}
}
Second constructor gets fired but the bar isn't styled. It actually appears as indeterminate spinning progress and none of these setup gets applied eventually - feels like those are overriden later by something else.
What's wrong here?
DISCLAIMER:
This is a very simple example. I'm perfectly aware I could go for styles or a simple xml implementation but I just use this simple case only to demonstrate the issue.
According to the bullet 5 of this article, you may need to modify initialSetup:
fun initialSetup() {
max = 100
isIndeterminate = false
progressDrawable = context.getDrawable(R.drawable.progress_bar)
invalidate()
requestLayout()
}
If it doesn't change anything, try calling initialSetup later, on onResume of activity/fragment for example. If this work, the problem is maybe linked to the complexity of initialization/lifecycle of android components.
I have a generic custom view like
class MyGenericCustomView<T>(context: Context, attrs: AttributeSet) : AnotherView(context, attrs) {
...
}
In the Activity/Fragment XML I have:
<package.name.MyGenericCustomView
android:id="#+id/custom_id"
....
/>
If I use the old way, I can get my "typed" custom view using something like:
override fun onCreate(...) {
...
val myCustomView = findViewById<MyGenericCustomView<String>>(R.id.custom_id)
...
}
But if I use the Android Kotlin Extension (synthetic) to have an object named with the same ID, I dont have a way to pass the Generic type, so
//custom_id is of type MyGenericCustomView<*>
One solution is to create a specific class like
class MySpecificCustomView(context: Context, attrs: AttributeSet) : MyGenericCustomView<String>(context, attrs) {
....
}
But I dont want to create this boilerplate class.
Is there any solution to specify a custom type using Kotlin Extensions only?
Thanks
Since you cannot specify the type parameter in the XML and type parameters are also erased in the byte code, you could simply cast the value to the proper generic type MyGenericCustomView<String>.
So something like that should work:
val myView = custom_id as MyGenericCustomView<String>
For better usage in your Activity/Fragment I would personally use lazy { } like this:
class MyActivity() : Activity(…) {
val myView by lazy { custom_id as MyGenericCustomView<String> }
...
}