我有一个布局的问题,我有一个线性布局(可以是相对布局或表格布局),当活动加载时,它将包含未定义数量的按钮。这意味着,按钮的数量将在创建活动时确定。问题是,我试图将它们都放在一行中(具有中心重力),而不改变每个按钮的宽度,直到它们中的一个到达屏幕的边缘。换句话说,我希望当按钮中至少有一个到达屏幕的边缘时,调整按钮的大小。这是因为,我无法确定它们将使用的空间,因为它们不是创建的。
我的实际线性布局:
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="40dp"
android:id="@+id/linearLayout_1"
android:layout_above="@+id/linearLayout_2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="30dp"
android:orientation="horizontal"
android:gravity="center"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true">
</LinearLayout>一段创建按钮的代码:
protected void hacerVisiblesRespuesta(){
ViewGroup linearLayout = (ViewGroup) findViewById(R.id.linearLayout);
assert linearLayout != null;
int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,40, getResources().getDisplayMetrics());
for(int i = 0; i < longuitudPalabra; i++){
String boton = "btn_rsp" + Integer.toString(i+1);
Button bt = new Button(this);
bt.setText("");
bt.setId(getResourceId(boton,"id",getPackageName()));
bt.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT
, height
, 1.0f));
bt.setTextColor(Color.BLACK);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clickBotonRespuesta(v);
}
});
bt.setVisibility(View.VISIBLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
bt.setBackground(getDrawable(R.drawable.bgbtnrsp));
}else{
//bt.setBackgroundDrawable(getDrawable(R.drawable.bgbtnrsp));
}
bt.setTextSize(20);
Typeface typeFace= Typeface.createFromAsset(getAssets(),"fonts/Montserrat-Regular.ttf");
bt.setTypeface(typeFace);
linearLayout.addView(bt);
}
}我尝试了很多方法,其中之一就是让按钮的宽度可以通过weight属性来改变。问题是,如果有少量的按钮,比方说4个,它们的宽度最终会变得很大。有没有办法通过代码来实现这一点呢?谢谢。
发布于 2016-06-07 14:51:58
你试过这个吗?
button.setLayoutParams (new LayoutParams(50, LayoutParams.WRAP_CONTENT)https://stackoverflow.com/questions/37668767
复制相似问题