自定义 按钮间,按钮边框滑动。

先是布局界面



                

                

                

                
            

然后是几个样式文件。


    
        
            
            
        
    
    
        
            
            
        
    


另一个border_button_background



    
    

    
    
        
            
        
    

使用代码

class YourFragment : Fragment() {

    private var selectedButton: Button? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_your_layout, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val buttons = listOf(btnOrderList, btnChargingOrderList, btnExceptionOrderList)
        val border = view.findViewById(R.id.border)

        buttons.forEachIndexed { index, button ->
            button.setOnClickListener {
                selectButton(button)
                animateBorder(button, border)
            }
        }

        // Set initial width of the border to match the first button
        val firstButton = buttons.first()
        border.layoutParams.width = firstButton.width
        border.requestLayout()
    }

    private fun selectButton(button: Button) {
        selectedButton?.isSelected = false
        button.isSelected = true
        selectedButton = button
    }

    private fun animateBorder(selectedButton: Button, border: View) {
        val targetX = selectedButton.x
        val targetWidth = selectedButton.width

        border.animate()
            .x(targetX)
            .scaleX(targetWidth / border.width.toFloat())
            .setDuration(300)
            .start()
    }
}

你可能感兴趣的:(kotlin,android,自定义效果,自定义控件)