Changing TabLayout icons on left, top, right or bottom in com.android.support:design:23.1.0

后端 未结 4 1841
走了就别回头了
走了就别回头了 2020-12-23 15:06

I\'m pretty new to android development. So bear with me.

I\'ve been trying to align the icon and text in same line in com.android.support:design:23.1.0

4条回答
  •  隐瞒了意图╮
    2020-12-23 15:33

    Actually, I have found a more elegant way (IMO) to do this without even using custom layouts, and just using the current default layout for tablayouts. Each tab layout item is in fact a Vertical LinearLayout, with the 1st item being an ImageView, and the 2nd item the TextView.

    So the method consists of changing the tab's LinearLayout orientation to Horizontal. After that, the icon will be positioned on the left. Now, if you want to position it on the right, you can remove the ImageView (which is the 1st item) and add it to the LinearLayout, it will be added as the last element so positioned at the end of the TextView, but you will have to play around with the layout params in order to display it aligned and sized correctly.

    So instead of re-adding the ImageView at the end of the LinearLayout, you can just add the drawable as a compound drawable to the TextView. add a little padding to it, and voila.

    LinearLayout tabItemLayout = (LinearLayout)((LinearLayout)tabLayout.getChildAt(0)).getChildAt(tabIndex);
    tabItemLayout.setOrientation(LinearLayout.HORIZONTAL);
    ImageView iconView = (ImageView) tabItemLayout.getChildAt(0);
    TextView textView = (TextView) tabItemLayout.getChildAt(1);
    // remove the icon view
    tabItemLayout.removeView(iconView);
    // add the icon as compound drawable
    textView.setCompoundDrawablesWithIntrinsicBounds(null, null, iconView.getDrawable(), null);
    // set some padding
    float DP = Resources.getSystem().getDisplayMetrics().density;
    int padding = (int)(10 * DP);
    textView.setCompoundDrawablePadding(padding);
    

    With this method, we don't need a custom layout and don't need to inflate anything, we just re-use the existing views.

提交回复
热议问题