我有一个 View ,其中有两个 LinearLayout - 一个包含文本、EditText 和一个按钮,另一个仅包含文本和 EditText。我试图让第二个 EditText (在第二行)的宽度与第一行的宽度相匹配。我尝试将其设为 TableLayout 而不是仅使用 LinearLayouts,现在尝试以编程方式设置宽度。我获取第一个 EditText 的宽度并尝试设置第二个 EditText 的宽度,但它不会改变大小。
* JAVA 调整大小尝试 *
@Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
getWidthBox = (EditText) findViewById(R.id.editText10);
setWidthBox = (EditText) findViewById(R.id.EditText01);
Toast.makeText(this, "Meaured Width: " + Integer.toString(getWidthBox.getMeasuredWidth()), Toast.LENGTH_SHORT).show();
Toast.makeText(this, "Get Width: " + Integer.toString(getWidthBox.getWidth()), Toast.LENGTH_SHORT).show();
//Neither of these setWidth Lines Work Correctly
setWidthBox.getLayoutParams().width=getWidthBox.getWidth();
setWidthBox.setWidth(getWidthBox.getWidth());
}
* XML 布局 *
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.15"
android:paddingLeft="5dp" >
<TextView
android:id="@+id/textView2"
android:layout_width="110dp"
android:layout_height="wrap_content"
android:layout_gravity="left|center_vertical"
android:text="Points Allowed: "
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="15sp" />
<EditText
android:id="@+id/editText10"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="number" >
</EditText>
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:src="@drawable/editpencil" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.15"
android:paddingLeft="5dp" >
<TextView
android:id="@+id/TextView01"
android:layout_width="110dp"
android:layout_height="wrap_content"
android:text="Points Used: "
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="15sp" />
<EditText
android:id="@+id/EditText01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="number" />
</LinearLayout>
* 模拟器的屏幕截图 *
最佳答案
我用一种对我来说最有意义的不同方式解决了这个问题。我所做的是通过 getWidth 获取铅笔按钮的宽度,然后将 LinearLayout 的右填充(每行都是它自己的 LinearLayout)设置为该按钮的宽度。这似乎工作得很好,并且允许按钮改变大小(基于屏幕大小和 DP)并且填充做出相应的 react 。
imageButtonWidth = (ImageButton) findViewById(R.id.imageButtonEdit);
linearLayoutPointsUsed= (LinearLayout) findViewById(R.id.linearPointsUsed);
widthOfEditButton = imageButtonWidth.getWidth();
linearLayoutPointsUsed.setPadding(5, 0, widthOfEditButton, 0);
关于Android EditText 以编程方式调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11492725/