gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 04:32:16 26 4
gpt4 key购买 nike

我有以下布局:

<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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com