Search code examples
androidkotlinandroid-layoutandroid-viewpagergravity

How to change gravity of a textview if the item isn't selected in Kotlin?


I have function onClick() to handle the selected item and apply changes on others if they are not selected. But I'm have a problem with the gravity.

this is the function:

@SuppressLint("NewApi", "ResourceAsColor")
override fun onClick(view: View) {
    if(view.id == R.id.item1) {
        item1.setTextColor(R.color.maincolor_purple)
        item1.background = ContextCompat.getDrawable(
            requireContext(),
            R.drawable.tab_bg_selected
        )
        item2.background = ContextCompat.getDrawable(
            requireContext(),
            R.drawable.tab_bg_unselected
        )
        item3.background = ContextCompat.getDrawable(
            requireContext(),
            R.drawable.tab_bg_unselected
        )
        item1.elevation = 3F
        item2.elevation = 2F
        item3.elevation = 1F
        item2.setTextColor(def);
        item3.setTextColor(def);
        viewPager2.setCurrentItem(0)
    } 
    else if (view.id == R.id.item2) {
        item1.setTextColor(def)
        item1.background = ContextCompat.getDrawable(
            requireContext(),
            R.drawable.tab_bg_unselected
        )
        item2.background = ContextCompat.getDrawable(
            requireContext(),
            R.drawable.tab_bg_selected
        )
        item3.background = ContextCompat.getDrawable(
            requireContext(),
            R.drawable.tab_bg_unselected
        )
        item2.setTextColor(R.color.maincolor_purple)

        item1.elevation = 1F
        item2.elevation = 3F
        item3.elevation = 2F
        item3.setTextColor(def)
        val size = item2.width
        viewPager2.setCurrentItem(1)
    }
    else if (view.id == R.id.item3) {
        item1.setTextColor(def)
        item1.background = ContextCompat.getDrawable(
            requireContext(),
            R.drawable.tab_bg_unselected
        )
        item2.background = ContextCompat.getDrawable(
            requireContext(),
            R.drawable.tab_bg_unselected
        )
        item3.background = ContextCompat.getDrawable(
            requireContext(),
            R.drawable.tab_bg_selected
        )
        item3.setTextColor(R.color.maincolor_purple)
        item1.elevation = 1F
        item2.elevation = 2F
        item3.elevation = 3F
        item2.setTextColor(def)
        val size = item2.width * 2
        viewPager2.setCurrentItem(2)
    }
}

So if any of these 3 selected and I want to apply on other to be left gravity.

I tried to add this:

item1.gravity = left

But it didn't work.

What is the correct way to achieve this?


Solution

  • SOLUTION:

    item.gravity = Gravity.RIGHT;