我想创建一个简单的计算器作为我的第一个 android 项目(而不是 Helloworld),calculaotr UI 如下所示,我用它GridLayout
来排列结果显示TextView
和控件Button
,GridLayout
需要 6 行和 4 列。(我在这里简化了xml布局文件)
<GridLayout android:rowCount="6"
android:columnCount="4"
android:orientation="horizontal">
<TextView android:id="@+id/expressionTextView"
android:layout_columnSpan="4"/>
<LinearLayout
android:layout_columnSpan="4">
<Button android:id="@+id/btnClearText"/>
<Button android:id="@+id/btnDeleteText"/>
</LinearLayout>
<GridLayout>
为了创建+/-/x//0-9.
按钮,我使用以下代码:
String[] buttonTexts = new String[]
{
"7", "8", "9", "/",
"4", "5", "6", "x",
"1", "2", "3", "-",
".", "0", "=", "+"
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Point size = new Point();
getWindowManager().getDefaultDisplay().getSize(size);
int screenWidth = size.x;
int screenHeight = size.y;
int oneQuarterWidth = (int) (screenWidth * 0.25);
for (int ii = 0; ii < buttonTexts.length; ii++) {
Button btn = new Button(this);
btn.setText(buttonTexts[ii]);
btn.setTextSize(40);
GridLayout.Spec rowSpec = GridLayout.spec(ii/4 + 2);
GridLayout.Spec columnSpec = GridLayout.spec(ii % 4 );
GridLayout.LayoutParams params = new GridLayout.LayoutParams(rowSpec, columnSpec);
params.setGravity(Gravity.FILL);
params.width = oneQuarterWidth;
gridLayout.addView(btn, params);
}
但是,最后一行在垂直方向上延伸,在我的android机器上运行计算器时,最后一行可能会隐藏一些!
我想要的是使 UI 适合设备高度,您有什么想法吗?谢谢!
PS我什至尝试设置结果显示的高度,TextView
其中LinearLayout
包含Clear/Del
使用:
expressionTextView = (TextView)findViewById(R.id.expressionTextView);
clearDelLinearLayout = (LinearLayout)findViewById(R.id.linearLayout1);
GridLayout.LayoutParams expressionTextViewParams =
(GridLayout.LayoutParams)expressionTextView.getLayoutParams();
expressionTextViewParams.height = ...; // some calculated height
expressionTextView.setLayoutParams(expressionTextViewParams);
但这不起作用:(