如何根据android中的文本内容动态设置按钮的宽度?

时间:2017-03-20 06:14:42

标签: android button android-linearlayout

我想根据文字内容确定按钮大小。例如,如果文本大小约为4个字母,那么按钮的宽度应该足够大,只能调整4个字母。这是我的代码:

layout = (LinearLayout) dialog.getCustomView().findViewById(R.id.layoutTags);
layout.setOrientation(LinearLayout.VERTICAL);  //Can also be done in xml by android:orientation="vertical"
layout.setWeightSum(1);
layout.removeAllViews();
layout.invalidate();
float rowneed = ((float) count1 / 5);
k = 0;
for (int i = 0; i < ceil(rowneed); i++) {
    LinearLayout row = new LinearLayout(getContext());
    row.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    row.removeAllViews();
    for (int j = 0; j < 5; j++) {
        btnTag = new Button(getContext());
        btnTag.setHeight(15);
        btnTag.setWidth(1);
        btnTag.setMinimumWidth(155);
        btnTag.setMinimumHeight(135);

        if (k < count1) {
            btnTag.setText(filteredTags.get(k).gettagName());
            btnTag.setId(k);
            k++;
            btnTag.setVisibility(View.VISIBLE);

        } else {
            btnTag.setVisibility(View.INVISIBLE);
        }
        Log.e("count", " " + k + " " + count1 + " " + ceil(rowneed) + " " + edtTag.getText().toString());
        btnTag.setTextSize(7);
        btnTag.setGravity(0);

        row.addView(btnTag);
    }
    layout.addView(row);
}

2 个答案:

答案 0 :(得分:0)

在java中设置LayoutParams

ViewGroup.LayoutParams p = button.getLayoutParams();
p.width= ViewGroup.LayoutParams.WRAP_CONTENT;
button.setLayoutParams(p);

答案 1 :(得分:0)

使用此:

button.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT,
1.0f));