作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下布局:
<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 并将其添加到 HorizontalScrollView。用户可以控制表中应显示哪些列。有时,如果用户选择了很多列,内容可能会溢出屏幕的宽度。大多数时候,表格小于屏幕的宽度,我希望它居中。如果不解决居中问题,上面的布局对于溢出屏幕的表格来说效果很好。例如。双向滚动都有效。但是,当我这样做时:
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/
我是一名优秀的程序员,十分优秀!