Created
October 13, 2021 11:28
-
-
Save veena14cs/5276db7aaa59841d9c2e65db594c655d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.oppia.android.app.customview | |
import android.content.Context | |
import android.text.TextUtils | |
import android.util.AttributeSet | |
import android.view.View | |
import androidx.appcompat.widget.AppCompatTextView | |
import androidx.core.view.ViewCompat | |
import androidx.fragment.app.Fragment | |
import androidx.fragment.app.FragmentManager | |
import org.oppia.android.app.translation.AppLanguageResourceHandler | |
import org.oppia.android.app.view.ViewComponentFactory | |
import org.oppia.android.app.view.ViewComponentImpl | |
import javax.inject.Inject | |
/** The custom Textview class for toolbar with Marquee effect. */ | |
class MarqueeToolbarTextView @JvmOverloads constructor( | |
context: Context, | |
attrs: AttributeSet? = null, | |
defStyle: Int = android.R.attr.textViewStyle | |
) : AppCompatTextView(context, attrs, defStyle), View.OnClickListener { | |
@Inject | |
lateinit var resourceHandler: AppLanguageResourceHandler | |
private val isRtl by lazy { | |
resourceHandler.getLayoutDirection() == ViewCompat.LAYOUT_DIRECTION_RTL | |
} | |
init { | |
setOnClickListener(this) | |
ellipsize = TextUtils.TruncateAt.MARQUEE | |
if (isRtl) { | |
textDirection = View.TEXT_DIRECTION_RTL | |
} else { | |
textDirection = View.TEXT_DIRECTION_LTR | |
} | |
} | |
override fun onClick(v: View?) { | |
isSelected = true | |
} | |
override fun onAttachedToWindow() { | |
super.onAttachedToWindow() | |
val viewComponentFactory = FragmentManager.findFragment<Fragment>(this) as ViewComponentFactory | |
val viewComponent = viewComponentFactory.createViewComponent(this) as ViewComponentImpl | |
viewComponent.inject(this) | |
} | |
} |
@veena14cs you can't use @Inject
constructors for Android classes. For views, we do field injection (see other custom views that inject fields for a reference).
For the current code, the reason you're getting not initialized error is because init{} is called as part of the constructor, and is trying to access resourceHandler which isn't initialized until inject(this) is called in onAttachedToWindow (which happens after construction). You'll need to move the text direction logic to happen in onAttachedToWindow() after injection.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I get error resourceHandler not initialized for above code.
and if I used @Inject for constructor
I get error
Caused by: java.lang.NoSuchMethodException: [class android.content.Context, interface android.util.AttributeSet]