如何在Android中的标签栏中居中对齐文本

sam*_*m_k 9 android

我想只在标签栏中放置文字,没有图像......我想在标签栏中水平和垂直居中.正好在中心.

se.*_*yev 32

如果有人仍然对简单的解决方案感兴趣而没有创建自己的布局

  1. 为每个添加的选项卡使用android.widget.TabHost.TabSpec #setIndicator(CharSequence标签)
  2. 使用下一个代码居中并在选项卡中包装文本:

    int tabCount = tabHost.getTabWidget().getTabCount();
    for (int i = 0; i < tabCount; i++) {
        final View view = tabHost.getTabWidget().getChildTabViewAt(i);
        if ( view != null ) {
            // reduce height of the tab
            view.getLayoutParams().height *= 0.66;
    
            //  get title text view
            final View textView = view.findViewById(android.R.id.title);
            if ( textView instanceof TextView ) {
                // just in case check the type
    
                // center text
                ((TextView) textView).setGravity(Gravity.CENTER);
                // wrap text
                ((TextView) textView).setSingleLine(false);
    
                // explicitly set layout parameters
                textView.getLayoutParams().height = ViewGroup.LayoutParams.FILL_PARENT;
                textView.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT;
            }
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)


exc*_*n01 2

您可以将其添加到 xml 布局android:gravity="center"android:layout_gravity="center"