Change Toast Font - android

Currently, I'm trying to develop an app.
and I don't know how to change the Toast font. .
final OnClickListener clickListener = new OnClickListener() {
public void onClick(View v) {
try {
Toast.makeText(nova.this,"Hello", 500000).show();
}
catch (Exception e) {
Toast.makeText(nova.this,"Exception:" +e, 500000);
}
}
};
I want to change the text "Hello" with custom font I've tried with TypeFace.
and Then, I want to set a variable at the place "TextClicked" .. I've tried with a local variable .. but it doesn't work
any help with example source code will be really great for me.

The answer is here: https://stackoverflow.com/a/13231981
After refactoring a little:
Toast toast = Toast.makeText(context, R.string.yummyToast, Toast.LENGTH_SHORT);
LinearLayout toastLayout = (LinearLayout) toast.getView();
TextView toastTV = (TextView) toastLayout.getChildAt(0);
toastTV.setTextSize(30);
toast.show();
This worked for me like a charm!

From the official documentation:
Create your custom ToastView
If a simple text message isn't enough, you can create a customized layout for your toast notification. To create a custom layout, define a View layout, in XML or in your application code, and pass the root View object to the setView(View) method.
Following the link to the official Google Documentation will provide examples.

You can use a SpannableString to set the font:
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/ATaha.ttf");
SpannableString efr = new SpannableString("Toast font changed!");
efr.setSpan(new TypefaceSpan(font), 0, efr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Toast.makeText(this, efr, Toast.LENGTH_SHORT).show();
A custom Span class that has a specific Typeface set:
public class TypefaceSpan extends MetricAffectingSpan {
private Typeface mTypeface;
public TypefaceSpan(Typeface typeface) {
mTypeface = typeface;
}
#Override
public void updateMeasureState(TextPaint p) {
p.setTypeface(mTypeface);
p.setFlags(p.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
}
#Override
public void updateDrawState(TextPaint tp) {
tp.setTypeface(mTypeface);
tp.setFlags(tp.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
}
}

Unfortunately the code on the Java page is bugged. Here is a link to a working function you can implement that gives you the text (I know, because I tested it), and with a little ingenuity, could be expanded to pass arguments for size, color, etc...
Toast Font size function here

Kotlin function:
fun makeLargeTextToast(text: CharSequence): Toast {
return Toast.makeText(applicationContext, text, Toast.LENGTH_LONG).also {
val toastLayout = it.view as LinearLayout
val toastTV = toastLayout.getChildAt(0) as TextView
toastTV.textSize = 30f
}
}
Use it as:
makeLargeTextToast("text message").show()

I used this solution in kotlin
in CustomView or Fragment
fun persianToast(message: String): Toast {
return Toast.makeText(context, message, Toast.LENGTH_SHORT).also {
val view = it.view as LinearLayout
val tv = view.getChildAt(0) as TextView
val typeFace = Typeface.createFromAsset(context?.assets, MyApplication.getFont(MyApplication.LIGHT_FONT))
tv.typeface = typeFace
}
}
MyApplication class :
class MyApplication : Application() {
companion object {
const val NORMAL_FONT = 0
const val BOLD_FONT = 1
const val MEDIUM_FONT = 2
const val LIGHT_FONT = 3
const val ULTRA_LIGHT_FONT = 4
#JvmStatic
fun getFont(type: Int): String {
return when (type) {
LIGHT_FONT -> "font/fontLight.ttf"
BOLD_FONT -> "font/fontBold.ttf"
MEDIUM_FONT -> "font/fontMedium.ttf"
ULTRA_LIGHT_FONT -> "font/fontUltraLight.ttf"
else -> "font/fontNormal.ttf"
}
}
}
used in fragment:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
Toast(context)
persianToast("javid sattar").show()
}
good luck!!

Related

Kotlin: Styling Text in Snackbar with SDK later than 28

I am working on a Kotlin project and I wish to style the text in a Snackbar, specifically the text font. I have been to many websites that address this problem, but they all use this line in the Snackbar body:
val snackbarTextView = snackbar.view.findViewById(android.support.design.R.id.snackbar_text) as TextView
The problem setting the TextView with this code, is that it only works if your project targets SDK 28 or older, and legacy libraries are enabled. I am targeting SDK 30 and then the element 'design' in that line is always an unresolved reference.
My Snackbar code is as follows:
private fun showSnackbar(message: String)
{
val coordinatorLayout: CoordinatorLayout = findViewById(R.id.coordinatorLayout)
val snackbar = Snackbar.make(coordinatorLayout, message, Snackbar.LENGTH_INDEFINITE)
snackbar.setBackgroundTint(Color.CYAN)
snackbar.setAction("DISMISS", View.OnClickListener {
// executed when DISMISS is clicked
})
snackbar.setTextColor(Color.BLACK)
snackbar.show()
}
I can set the text color and size, but not other attributes like the font. How can I do this in Kotlin with the later SDKs? Thanks!
from here
suppose you have your custom font inside res>font>myfont.ttf
create this class:
class CustomTypefaceSpan(var typeface: Typeface) : MetricAffectingSpan() {
override fun updateDrawState(ds: TextPaint) {
applyCustomTypeFace(ds, typeface)
}
override fun updateMeasureState(paint: TextPaint) {
applyCustomTypeFace(paint, typeface)
}
private fun applyCustomTypeFace(paint: Paint, tf: Typeface) {
paint.typeface = tf
}
}
then :
private fun showSnackbar(message: String) {
val ss = SpannableStringBuilder(message)
val font = ResourcesCompat.getFont(this, R.font.myfont)
ss.setSpan(CustomTypefaceSpan(font!!), 0, message.length, Spanned.SPAN_EXCLUSIVE_INCLUSIVE)
val coordinatorLayout: CoordinatorLayout = findViewById(R.id.coordinatorLayout)
val snackbar = Snackbar.make(coordinatorLayout, ss, Snackbar.LENGTH_INDEFINITE)
snackbar.setBackgroundTint(Color.CYAN)
snackbar.setAction("DISMISS", View.OnClickListener {
// executed when DISMISS is clicked
})
snackbar.setTextColor(Color.BLACK)
snackbar.show()
}

Custom Rating Bar using Anko

I've been exploring android development using Anko and Kotlin and had some trouble with the ratingbar, namely it size. I've tried to make it smaller using a custom style but themedRatingBar doesn't seem to work. So I've opted to make a custom ratingbar instead. I can't seem to make it work that way I want it to in that when I set it this way in the main activity:
starRatingView{
setRating(3)
}
It does not output a rating of 3 and instead will output the default rating, which is zero.
class StarRatingView: _LinearLayout {
lateinit var imageViewStars: List<ImageView>
private var starNum: Float = 0f
private var starSize: Int = 5
constructor(context: Context): super(context) {
initializeView()
}
fun initializeView() {
with(this) {
linearLayout {
relativeLayout {
linearLayout {
for (i in 1..starSize)
imageView(R.drawable.ratingbar_empty)
}
linearLayout {
for (i in 0..Math.round(starNum)) {
imageView(R.drawable.ratingbar_filled)
}
}
}
}
}
}
fun setSize(starSize: Int){
this.starSize = starSize
}
fun setRating(starNum: Float){
this.starNum = starNum
}
}
Above is the code that I use to create the custom RatinBar. Trying to avoid using XMLs as much as possible and use Anko instead.
if I can help here is a possible solution to show a custom RatingBar in a custom Alert using Anko library and Kotlin code...
var rateGave: String? = null
alert {
title = "Rate your experience"
customView {
linearLayout {
ratingBar {
numStars = 5 //here is to define the number of stars you want
rating = 4f //starting rate to show as the alert pop up
setOnRatingBarChangeListener { ratingBar, rating, fromUser ->
rateGave = rating.toString()
}
}
}
}
positiveButton("Rate") { rate() }
}.show()
}
fun rate() {
println(rateGave) //now it's just printing out the rate to show that it's working fine, but in this function you can mange all the operations you need with the rating value
}
Hope it can be usefull.
Have a nice day :)

How to have an image with a dynamic text in it, all in a drawable, like the "today" action item on Google Calendar app?

Background
Google Calendar app has an action item that dynamically change according to the current day ("today"):
I'm required to do a very similar thing, but with a slightly different image that surrounds the text.
The problem
I did succeed to make it work, by creating a Drawable that has text and image in it (based on here).
However, I'm don't think I did it well enough :
Text font might be different across devices, so might not fit well in what I wrote.
Not sure if it's because of the VectorDrawable or the text, but I think the text doesn't seem so centered . Seems a bit to the left. This is especially true if I use 2 digits:
For centering vertically, I don't think I did the correct calculation. I tried much more logical things there, but they were not centered.
What I've tried
Here's the full code (also available here in a project) :
TextDrawable.java
public class TextDrawable extends Drawable {
private static final int DEFAULT_COLOR = Color.WHITE;
private static final int DRAWABLE_SIZE = 24;
private static final int DEFAULT_TEXT_SIZE = 8;
private Paint mPaint;
private CharSequence mText;
private final int mIntrinstSize;
private final Drawable mDrawable;
public TextDrawable(Context context, CharSequence text) {
mText = text;
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setColor(DEFAULT_COLOR);
mPaint.setTextAlign(Align.CENTER);
float textSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DEFAULT_TEXT_SIZE, context.getResources().getDisplayMetrics());
mPaint.setTextSize(textSize);
mIntrinstSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DRAWABLE_SIZE, context.getResources().getDisplayMetrics());
mDrawable = AppCompatResources.getDrawable(context, R.drawable.ic_backtodate);
mDrawable.setBounds(0, 0, mIntrinstSize, mIntrinstSize);
}
#Override
public void draw(Canvas canvas) {
Rect bounds = getBounds();
mDrawable.draw(canvas);
canvas.drawText(mText, 0, mText.length(),
bounds.centerX(), bounds.centerY() + mPaint.getFontMetricsInt(null) / 3, mPaint); // this seems very wrong
}
#Override
public int getOpacity() {
return mPaint.getAlpha();
}
#Override
public int getIntrinsicWidth() {
return mIntrinstSize;
}
#Override
public int getIntrinsicHeight() {
return mIntrinstSize;
}
#Override
public void setAlpha(int alpha) {
mPaint.setAlpha(alpha);
}
#Override
public void setColorFilter(ColorFilter filter) {
mPaint.setColorFilter(filter);
}
}
MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val drawable = TextDrawable(this, "1")
imageView.setImageDrawable(drawable)
}
}
ic_backtodate.xml
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="25dp" android:height="25dp"
android:viewportHeight="76.0" android:viewportWidth="76.0">
<path
android:fillColor="#ffffff" android:fillType="evenOdd"
android:pathData="M47.294,60.997H28.704C21.148,60.997 15,54.755 15,47.083V28.905c0,-7.672 6.148,-13.913 13.704,-13.913h18.59C54.852,14.992 61,21.233 61,28.905v18.178c0,7.672 -6.148,13.914 -13.706,13.914zM57.592,28.905c0,-5.763 -4.62,-10.453 -10.298,-10.453h-18.59c-5.676,0 -10.296,4.69 -10.296,10.453v18.178c0,5.765 4.62,10.454 10.296,10.454h18.59c5.678,0 10.298,-4.689 10.298,-10.454z"/>
</vector>
The questions
How can I overcome the different fonts issues? I already use "Lato" font globally (not in the sample app, but in the real app, using "downloaded fonts" API of the support library, but having them built into the app instead), but I don't think Paint Object can use it, right?
How can I center the text well?
I've looked, via View-hierarchy tool, at how Google Calendar works for this part. To me it seems they just used TextView. How did they do it? Maybe using a 9-patch? But does it work well for Toolbar items?
EDIT:
For now, because I'm tight on schedule, I can't use the drawable solution. Would still be nice to know how to do it well.
My current solution doesn't involve it. I just use a special view that mimics a normal action item. It's not perfect (doesn't fully mimics a real action item), but it will be enough for now. Because it's not perfect, I wrote about it on a new thread, here.
EDIT: since this actually can work well, and still stay as a normal action item, I've decided to give it another try.
I've managed to center the text nicely, but the font is the issue now. It seems that if the OS uses a font of its own, even if I've set "Lato" to be the one of the app, it's not used in the drawable I've made:
I think it's the last issue I need to fix here.
Here's the code:
styles.xml
<item name="android:fontFamily" tools:targetApi="jelly_bean">#font/lato</item>
<item name="fontFamily">#font/lato</item>
MainActivity.kt
class MainActivity : AppCompatActivity() {
lateinit var textDrawable: TextDrawable
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
textDrawable = TextDrawable(this, "1")
setSupportActionBar(toolbar)
val handler = Handler()
val runnable = object : Runnable {
var i = 1
override fun run() {
if (isFinishing||isDestroyed)
return
textDrawable.text = (i + 1).toString()
i = (i + 1) % 31
handler.postDelayed(this, 1000)
}
}
runnable.run()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menu.add("goToToday").setIcon(textDrawable).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
menu.add("asd").setIcon(R.drawable.abc_ic_menu_copy_mtrl_am_alpha).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
return super.onCreateOptionsMenu(menu)
}
}
TextDrawable.kt
class TextDrawable(context: Context, text: CharSequence) : Drawable() {
companion object {
private val DEFAULT_COLOR = Color.WHITE
private val DEFAULT_TEXT_SIZE = 12
}
var text: CharSequence = text
set (value) {
field = value
invalidateSelf()
}
private val mPaint: TextPaint = TextPaint(Paint.ANTI_ALIAS_FLAG)
private val mDrawable: Drawable?
init {
mPaint.color = DEFAULT_COLOR
mPaint.textAlign = Align.CENTER
val textSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DEFAULT_TEXT_SIZE.toFloat(), context.resources.displayMetrics)
mPaint.textSize = textSize
mDrawable = AppCompatResources.getDrawable(context, R.drawable.ic_backtodate)
mDrawable!!.setBounds(0, 0, mDrawable.intrinsicWidth, mDrawable.intrinsicHeight)
}
override fun draw(canvas: Canvas) {
val bounds = bounds
mDrawable!!.draw(canvas)
canvas.drawText(text, 0, text.length,
bounds.centerX().toFloat(), (bounds.centerY() + mPaint.getFontMetricsInt(null) / 3).toFloat(), mPaint) // this seems very wrong, but seems to work fine
}
override fun getOpacity(): Int = mPaint.alpha
override fun getIntrinsicWidth(): Int = mDrawable!!.intrinsicWidth
override fun getIntrinsicHeight(): Int = mDrawable!!.intrinsicHeight
override fun setAlpha(alpha: Int) {
mPaint.alpha = alpha
invalidateSelf()
}
override fun setColorFilter(filter: ColorFilter?) {
mPaint.colorFilter = filter
invalidateSelf()
}
}
EDIT:
I think I've found how to have a font for the text, by using :
mPaint.typeface=TypefaceCompat.createFromResourcesFamilyXml(...)
Not sure though how to fill the parameters. Still investigating...
OK, found the answer about how to have the same font for the TextPaint of the Drawable class I've made:
mPaint.typeface = ResourcesCompat.getFont(context, R.font.lato)
The result:
Here's the full implementation of this class:
class TextDrawable(context: Context, text: CharSequence) : Drawable() {
companion object {
private val DEFAULT_COLOR = Color.WHITE
private val DEFAULT_TEXT_SIZE_IN_DP = 12
}
private val mTextBounds = Rect()
private val mPaint: TextPaint = TextPaint(Paint.ANTI_ALIAS_FLAG)
private val mDrawable: Drawable?
var text: CharSequence = text
set (value) {
field = value
invalidateSelf()
}
init {
mPaint.typeface = ResourcesCompat.getFont(context, R.font.lato)
mPaint.color = DEFAULT_COLOR
mPaint.textAlign = Align.CENTER
val textSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DEFAULT_TEXT_SIZE_IN_DP.toFloat(), context.resources.displayMetrics)
mPaint.textSize = textSize
mDrawable = AppCompatResources.getDrawable(context, R.drawable.ic_backtodate)
mDrawable!!.setBounds(0, 0, mDrawable.intrinsicWidth, mDrawable.intrinsicHeight)
}
override fun draw(canvas: Canvas) {
val bounds = bounds
mDrawable!!.draw(canvas)
mPaint.getTextBounds(text.toString(), 0, text.length, mTextBounds);
val textHeight = mTextBounds.bottom - mTextBounds.top
canvas.drawText(text as String?, (bounds.right / 2).toFloat(), (bounds.bottom.toFloat() + textHeight + 1) / 2, mPaint)
}
override fun getOpacity(): Int = mPaint.alpha
override fun getIntrinsicWidth(): Int = mDrawable!!.intrinsicWidth
override fun getIntrinsicHeight(): Int = mDrawable!!.intrinsicHeight
override fun setAlpha(alpha: Int) {
mPaint.alpha = alpha
invalidateSelf()
}
override fun setColorFilter(filter: ColorFilter?) {
mPaint.colorFilter = filter
invalidateSelf()
}
}
EDIT: this code is now complete and works well. It should work fine, and is partially based on Calendar app itself, as was recommended to me to look at (here and here) .
Reference is made to your other question "How to fully mimic Action item view in the toolbar, for a customized one?"
I have incorporated the approach in my answer to the above-referenced question into your implementation of a custom drawable in your answer to this question. Below is a new version of TextDrawable.java that dynamically builds a boxed TextView for display as the desired icon for a menu item. It avoids drawing caches and simply manages a TextView internally for display.
TextDrawable.java
public class TextDrawable extends Drawable {
private final int mIntrinsicSize;
private final TextView mTextView;
public TextDrawable(Context context, CharSequence text) {
mIntrinsicSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DRAWABLE_SIZE,
context.getResources().getDisplayMetrics());
mTextView = createTextView(context, text);
mTextView.setWidth(mIntrinsicSize);
mTextView.setHeight(mIntrinsicSize);
mTextView.measure(mIntrinsicSize, mIntrinsicSize);
mTextView.layout(0, 0, mIntrinsicSize, mIntrinsicSize);
}
private TextView createTextView(Context context, CharSequence text) {
TextView textView = new TextView(context);
// textView.setId(View.generateViewId()); // API 17+
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER;
textView.setLayoutParams(lp);
textView.setGravity(Gravity.CENTER);
textView.setBackgroundResource(R.drawable.ic_backtodate);
textView.setTextColor(Color.WHITE);
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, DEFAULT_TEXT_SIZE);
textView.setText(text);
return textView;
}
public void setText(CharSequence text) {
mTextView.setText(text);
invalidateSelf();
}
#Override
public void draw(#NonNull Canvas canvas) {
mTextView.draw(canvas);
}
#Override
public int getOpacity() {
return PixelFormat.OPAQUE;
}
#Override
public int getIntrinsicWidth() {
return mIntrinsicSize;
}
#Override
public int getIntrinsicHeight() {
return mIntrinsicSize;
}
#Override
public void setAlpha(int alpha) {
}
#Override
public void setColorFilter(ColorFilter filter) {
}
private static final int DRAWABLE_SIZE = 32; // device-independent pixels (DP)
private static final int DEFAULT_TEXT_SIZE = 12; // device-independent pixels (DP)
}
Invoke this custom Drawable as follows (Kotlin):
mTextDrawable = TextDrawable(this, "1")
menu.add("goToToday").setIcon(mTextDrawable).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
To change the displayed date (Kotlin):
mTextDrawable?.setText(i.toString())

How to use selectableButtonBackground on Anko?

How do I use selectableButtonBackground attribute on a custom View that uses Anko's apply() method inside its constructor like the following structure?
class XPTO(context: Context) : CardView(context) {
init {
this.apply {
// I'd like to invoke selectableButtonBackground here
}
}
I've tried to do context.obtainStyledAttributes(arrayOf(R.attr.selectableItemBackground).toIntArray()).getDrawable(0) but with no success.
I just created an extension function to get the resource ids for attributes.
val Context.selectableItemBackgroundResource: Int get() {
return getResourceIdAttribute(R.attr.selectableItemBackground)
}
fun Context.getResourceIdAttribute(#AttrRes attribute: Int) : Int {
val typedValue = TypedValue()
theme.resolveAttribute(attribute, typedValue, true)
return typedValue.resourceId
}
This way you can also add more attributes if needed. Example to put it in anko:
frameLayout {
textView {
text = "Test"
backgroundResource = selectableItemBackgroundResource
isClickable = true
}
}
Don't forget the isClickable, else you won't see anything when you're clicking the textView
Another way to achieve this with Anko:
val backgroundResource = attr(R.attr.selectableItemBackgroundBorderless).resourceId

How to reference other views in Anko DSL?

I'm using Anko in my Android project, but I don't know how can it reference the child views I created in the DSL when the referenced view is not at the same level where I reference it.
The following code works:
alert {
customView {
val input = textInputLayout {
editText {
hint = "Name"
textColor =resources.getColor(R.color.highlight)
}
}
positiveButton("OK") { "${input.editText.text}" }
}
}.show()
but the following code does not work:
alert {
customView {
val vertical = verticalLayout {
textView {
text = "Edit device name"
textColor = resources.getColor(R.color.highlight)
textSize = 24F
}
val input = textInputLayout {
editText {
hint = "Name"
textColor = resources.getColor(R.color.highlight)
}
}
}
positiveButton("OK") { "${vertical.input.editText.text}" } // Cannot resolve "input"
}
}.show()
As I see it there are two ways. The super hacky way would be to declare the positive button within the textInputLayout block. This is possible because you can access all outer scopes from within any nested scope and the positiveButton method is declared in the alert scope:
alert {
customView {
verticalLayout {
textInputLayout {
val editText = editText {
hint = "Name"
}
positiveButton("OK") { toast("${editText.text}") }
}
}
}
}.show()
The less hacky way would be to declare a variable that can be accessed from both scopes. However you would need to make it nullable since you can't initialize it immediately:
alert {
var editText: EditText? = null
customView {
verticalLayout {
textInputLayout {
editText = editText {
hint = "Name"
}
}
}
}
positiveButton("OK") { toast("${editText!!.text}") }
}.show()
I propose using findViewById()
alert {
customView {
val vertical = verticalLayout {
textView {
text = "Edit device name"
textSize = 24F
}
val input = textInputLayout {
editText {
id = R.id.my_id_resource // put your id here
hint = "Name"
}
}
}
positiveButton("OK") { "${(vertical.findViewById(R.id.my_id_resource) as? EditText)?.text}" }
}
}.show()
You can always elevate a view, passing the context vertical manually:
customView {
val vertical = verticalLayout {
textView {
text = "Edit device name"
textColor = resources.getColor(R.color.highlight)
textSize = 24F
}
}
val input = /*here:*/ vertical.textInputLayout {
editText {
hint = "Name"
textColor = resources.getColor(R.color.highlight)
}
}
positiveButton("OK") { "${input.editText.text}" }
}
I usually declare a view as a property in a class with lateinit modifier; this way it's not nullable and most of views are declared in one place, improving readability:
lateinit var toolbar: Toolbar
...
appBarLayout {
toolbar = toolbar {}.lparams(width = matchParent, height = matchParent)
}.lparams(width = matchParent)
...
setSupportActionBar(toolbar)
Probably the best way is to use Android IDs for the elements you need to reference later, and the find<T : View>(Int) : T function. This allows you to reference them from anywhere, as long as the view still exists, and you have access to the application/activity scope.
See the Anko Documentation for details
Example case: Dynamically adding buttons to an existing view
verticalLayout {
id = R.id.button_container
}
//note that the code below here may be executed anywhere after the above in your onCreate function
//verticalLayout is a Anko subclass of LinearLayout, so using the android class is valid.
val buttonContainer = find<LinearLayout>(R.id.button_container)
val containerContext = AnkoContext.Companion.create(ctx, buttonContainer)
val button = ctx.button {
text = "click me"
onClick = { toast("created with IDs!") }
}
buttonContainer.addView(button.createView(containerContext, buttonContainer))

Categories

Resources