我试图创建一个类似于拨号的GridLayout,类似于这个草图:
我未能正确创建它。
我的想法是所有单元格都占用相同的空间,均匀分布大小,除了右侧的退格按钮,超过3行。
我现在拥有的是:
private TextView generateGridTextButton(final CharSequence textToShowAndAddUponClick) {
TextView tv = (TextView) LayoutInflater.from(this).inflate(R.layout.grid_text_button, mButtonsGrid, false);
tv.setText(textToShowAndAddUponClick);
tv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View view) {
//...
}
});
return tv;
}
private void initButtonsGrid() {
for (int i = 1; i <= 3; ++i)
mButtonsGrid.addView(generateGridTextButton(Integer.toString(i)));
final ImageView backspaceButton = new ImageView(this);
backspaceButton.setImageResource(android.R.drawable.sym_def_app_icon);
final LayoutParams backspaceButtonLayoutParams = new LayoutParams(GridLayout.spec(GridLayout.UNDEFINED, 3, 3), GridLayout.spec(GridLayout.UNDEFINED, 1, 1));
backspaceButtonLayoutParams.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
backspaceButtonLayoutParams.height = backspaceButtonLayoutParams.width = LayoutParams.WRAP_CONTENT;
backspaceButton.setLayoutParams(backspaceButtonLayoutParams);
backspaceButton.setBackground(...));
mButtonsGrid.addView(backspaceButton);
for (int i = 4; i <= 9; ++i)
mButtonsGrid.addView(generateGridTextButton(Integer.toString(i)));
backspaceButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View view) {
//...
}
});
mButtonsGrid.addView(generateGridTextButton("*"));
mButtonsGrid.addView(generateGridTextButton("0"));
mButtonsGrid.addView(generateGridTextButton("+"));
final ImageView actionButton = new ImageView(this);
actionButton.setImageResource(android.R.drawable.sym_def_app_icon);
final LayoutParams actionButtonLayoutParams = new LayoutParams(GridLayout.spec(GridLayout.UNDEFINED, 1, 1), GridLayout.spec(GridLayout.UNDEFINED, 1, 1));
actionButtonLayoutParams.setGravity(Gravity.CENTER);
actionButtonLayoutParams.height = actionButtonLayoutParams.width = LayoutParams.WRAP_CONTENT;
actionButton.setLayoutParams(actionButtonLayoutParams);
actionButton.setBackground(...);
actionButton.setClickable(true);
mButtonsGrid.addView(actionButton);
}
RES /布局/ grid_text_button.xml
<TextView
xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_rowWeight="1"
android:background="@drawable/..." android:clickable="true" android:fontFamily="..."
android:gravity="center" android:textColor="#2a373e" android:textSize="36sp" app:layout_columnWeight="1"
app:layout_gravity="fill" tools:text="1"/>
布局文件包含:
<android.support.v7.widget.GridLayout android:id="@+id/gridLayout"
... app:columnCount="4"
app:orientation="horizontal" app:rowCount="4">
这几乎可以工作但是出于某种原因,2个顶行按钮的高度比2个底行按钮的高度要小:
我尝试使用重力,重量,跨度的值...但我尝试的任何事情都没有帮助(甚至变得更糟)。
这里有什么问题?为什么行的高度不同?
我该如何解决这个问题?