我想创建方形按钮,但是因为我无法通过 XML 获取宽度以将其分配给按钮的高度,所以我使用 Java 来完成。所以我这样做:
View body = inflater.inflate(R.layout.picker_numeric, null);
Button up = (Button) body.findViewById(R.id.picker_numeric_up);
Log.d(TAG, "" + up.getWidth());
int height = up.getWidth();
up.setHeight(height);
........................
AlertDialog.Builder builder = new AlertDialog.Builder(activity)
.setTitle(title)
.setView(body)
........................
我曾经Log.d
确认getWidth()
返回 0。有人知道为什么会这样吗?我别无选择。
编辑:在MKJParekh和Simon说我的代码之后是这样的:
对话框内容.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/picker_numeric_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:baselineAligned="false"
android:padding="@dimen/padding_small"
android:weightSum="3"
tools:ignore="HardcodedText,UselessParent" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<Button
android:id="@+id/picker_numeric_up"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/padding_medium"
android:layout_marginRight="@dimen/padding_medium"
android:gravity="center"
android:text="+" />
<EditText
android:id="@+id/picker_numeric_value"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/padding_medium"
android:layout_marginRight="@dimen/padding_medium"
android:gravity="center"
android:inputType="number" />
<Button
android:id="@+id/picker_numeric_down"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/padding_medium"
android:layout_marginRight="@dimen/padding_medium"
android:gravity="center"
android:text="-" />
</LinearLayout>
</LinearLayout>
对话框的创建者类中的方法:
public void equalDimens() {
up.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int height = up.getMeasuredWidth();
android.util.Log.d("dd", ""+height);
up.setLayoutParams(new LinearLayout.LayoutParams(height, height));
down.setLayoutParams(new LinearLayout.LayoutParams(height, height));
}
然后在 Activity 的类中:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
createMyDialog();
LinearLayout mainLayout = (LinearLayout ) this.getLayoutInflater().inflate(R.layout.main, null);
mainLayout.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
myDialogClass.equalDimens();
}
});
setContentView(mainLayout);
}
不打电话myDialogClass.equalDimens()
我得到这个:
并调用我得到的方法: