正如您从这张图片中看到的那样,我一直在尝试使用方形 child 来实现 GridLayout
。
所以基本上 View 应该根据项目的数量进行调整,而不需要我声明列大小和行大小。这对 GridLayout
有可能吗?如果没有,那就忘记这个问题。
现在让我们进入正方形部分。我尝试实现此代码
public class SquareLinearLayout extends LinearLayout {
public SquareLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int widthSize = MeasureSpec.getSize(widthMeasureSpec);
final int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if (widthSize == 0 && heightSize == 0) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
final int minSize = Math.min(getMeasuredWidth(), getMeasuredHeight());
setMeasuredDimension(minSize, minSize);
return;
}
final int size;
if (widthSize == 0 || heightSize == 0) {
size = Math.max(widthSize, heightSize);
} else {
size = Math.min(widthSize, heightSize);
}
final int newMeasureSpec = MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY);
super.onMeasure(newMeasureSpec, newMeasureSpec);
}
}
尽管它确实使子布局成为正方形,但它也占据了屏幕的整个宽度,将其他子项推出了布局的可见部分。
你有任何链接或者你自己有一个类似于这个类但不占据整个布局宽度的代码吗?提前致谢。
最佳答案
从来没有我使用上面相同的代码让它工作,并将项目放在 TableLayout 而不是 Gridlayout 中。
如果您像我一样陷入这种情况,这里有一个示例代码。首先,我为正方形创建一个布局。
<?xml version="1.0" encoding="utf-8"?>
<com.android.f45tv.view.ui.SquareLinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/sllContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="2dp"
android:orientation="vertical">
<LinearLayout
android:id="@+id/llHolder"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="2dp"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="@+id/tvName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textColor="@color/white"
android:layout_marginBottom="2dp"
android:gravity="center_horizontal" />
<TextView
android:id="@+id/tvPercent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="40sp"
android:textColor="@color/white"
android:gravity="center" />
<TextView
android:id="@+id/tvBPM"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/white"
android:textSize="12sp"
android:gravity="end" />
<TextView
android:id="@+id/tvBPMLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="bpm"
android:textSize="10sp"
android:textColor="@color/white"
android:gravity="end" />
</LinearLayout>
</com.android.f45tv.view.ui.SquareLinearLayout>
然后将它添加到我的主要 Activity 布局中,并在表格行中使用
include
标记。关于android - 带有方形子元素的网格布局,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35173185/