如果在 Kotlin 中未选择项目,如何更改文本视图的重力?

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

我有功能 onClick() 来处理所选项目并在其他项目未被选中时应用更改。但是我的重力有问题。

这是函数:

@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)
    }
}

因此,如果选择了这 3 个中的任何一个,并且我想将其应用于其他左引力。

我试着添加这个:

item1.gravity = left

但是没有用。

实现这个的正确方法是什么?

解决方案:

item.gravity = Gravity.RIGHT;