Add Icons+Text to TabLayout

前端 未结 3 441
再見小時候
再見小時候 2020-12-02 10:02

I am working on a screen which contains Three tabs I am trying to add an icon with My text in tabs and i want the image to be upper the text and there should be some space b

3条回答
  •  既然无缘
    2020-12-02 10:47

    If you want to put icons and text in a single line in a tablayout you have to make a custom layout as below.

    custom_tab_heading.xml

    
    
        
    
    

    At your java side you can write below code to put image and title to your tabs.

    val tabTitles = arrayListOf("  Text Jokes","  Funny Images")
    val tabIcons = arrayListOf(R.drawable.text_jokes,R.drawable.image_jokes)
    
    
    val tabLinearLayout = LayoutInflater.from(context).inflate(R.layout.custom_tab_heading, null) as LinearLayout
    val tabContent = tabLinearLayout.findViewById(R.id.tabContent) as TextView
    tabContent.text = tabTitles.get(0)
    tabContent.setCompoundDrawablesWithIntrinsicBounds(tabIcons[0], 0, 0, 0)
    myTabLayout.getTabAt(0)!!.setCustomView(tabContent)
    
    val tabLinearLayout1 = LayoutInflater.from(context).inflate(R.layout.custom_tab_heading, null) as LinearLayout
    val tabContent1 = tabLinearLayout1.findViewById(R.id.tabContent) as TextView
    tabContent1.text = tabTitles.get(1)
    tabContent1.setCompoundDrawablesWithIntrinsicBounds(tabIcons[1], 0, 0, 0)
    var l = tabLinearLayout1.layoutParams
    myTabLayout.getTabAt(1)!!.setCustomView(tabContent1)
    

    Note:- In tabTitles array notice that i have given a space before text(Title 1) because it will keep space between your image and title.

    Sorry for i am providing kotlin code here but you can easily convert it to java. If anyone having a problem then comment in this answer and i will try to help them.

提交回复
热议问题