android - 如何将内容有时比屏幕宽的 Android 表格居中?

标签 android android-layout

我有以下布局:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scrollViewFrameLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginBottom="30dip">
    <ScrollView
        android:id="@+id/verticalScrollContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingTop="10dip">
        <HorizontalScrollView
            android:id="@+id/horizontalScrollContainer"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </HorizontalScrollView>
    </ScrollView>
</FrameLayout>

对于水平滚动容器,我以编程方式创建了一个 TableLayout 并将其添加到 Horizo​​ntalScrollView。用户可以控制表中应显示哪些列。有时,如果用户选择了很多列,内容可能会溢出屏幕的宽度。大多数时候,表格小于屏幕的宽度,我希望它居中。如果不解决居中问题,上面的布局对于溢出屏幕的表格来说效果很好。例如。双向滚动都有效。但是,当我这样做时:

FrameLayout.LayoutParams lp = 
     new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, 
                  LayoutParams.WRAP_CONTENT, Gravity.CENTER);
theTable.setLayoutParams(lp);

它开始表现得很奇怪。当内容小于屏幕宽度时,它会正确地将其居中。但是,当内容比屏幕宽时,内容会居中,迫使表格左侧的部分内容从屏幕左侧消失。例如

    SSSSSS
    SSSSSS
  TTTTTTTTTT
    SSSSSS
    SSSSSS

其中“S”是屏幕,“T”是表格。也无法向左滚动以查看截断的内容(但向右滚动可以)。我在找什么:

如果表格小于屏幕宽度,则将其居中。 如果表格比屏幕宽,则左对齐并水平滚动。

关于如何实现这一点有什么想法吗?

最佳答案

对此的解决方案涉及挂接到我的表格的 onGlobalLayoutListener,它在布局完成后触发(因此我可以访问表格的显示宽度)。这是代码:

    final TableLayout table = (TableLayout)findViewById(R.id.the_table);
    ViewTreeObserver vto = table.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener()
    {
        public void onGlobalLayout()
        {
            ViewTreeObserver obs = table.getViewTreeObserver();
            obs.removeGlobalOnLayoutListener(this);

            int screenWidth = 
                       activity.getWindowManager().getDefaultDisplay().getWidth();


            //If the table is smaller than the screen width, setup new layout
            //parameters to center the table.  Otherwise, leave the table left 
            //aligned
            if (table.getWidth() < screenWidth)
            {
                FrameLayout.LayoutParams lp = 
                      new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, 
                              LayoutParams.WRAP_CONTENT, Gravity.CENTER);
                table.setLayoutParams(lp);
            }
        }

关于android - 如何将内容有时比屏幕宽的 Android 表格居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7492305/

相关文章:

android - 我的应用程序未在 android 市场中显示,但仅在某些情况下显示

android - 从 android 上的视频中检索任意帧

Android - ScrollView 从底部开始

java - Android中如何更改listView的字体?

android - 当父 View 未填满整个屏幕时, fragment 中的中心项目

android - 添加 lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER) 不适用于立方折线图

java - 如何使用 Google Sign in 授权 Youtube Data api 请求?

android - 无法在android应用程序中打开pdf

android - 平板电脑和智能手机上的布局单元

android - 使用自定义行为为 CollapsingToolbar 创建多个 "anchor points"/位置