有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

安卓无法通过Java代码使按钮变宽

我不知道是什么问题。我正在创建一个简单的电话簿,所以我有一个名字的名字,图像和呼叫按钮下的名字。当我尝试使用按钮的layoutParams参数设置宽度时,它不会改变任何东西,btn.setWidth();也不起作用

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    final LinearLayout linear = (LinearLayout)findViewById(R.id.linear);
        LinearLayout.LayoutParams sublparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        LinearLayout.LayoutParams childparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        LinearLayout.LayoutParams imageparams = new LinearLayout.LayoutParams(200, 200);
        linear.setOrientation(LinearLayout.VERTICAL);
        for(int i = 0; i < 10 ; i++){
            LinearLayout sublinear = new LinearLayout(this);
            Button btn = new Button(this);
            ImageView img = new ImageView(this);
            TextView txt = new TextView(this);
            img.setImageResource(R.drawable.img);
            txt.setText("Abonent " + (i+1));
            btn.setBackgroundColor(getColor(R.color.mygreen));
            btn.setText("+3800000");
            txt.setLayoutParams(childparams);
            btn.setLayoutParams(imageparams);
            img.setLayoutParams(imageparams);
            linear.addView(txt);
            sublinear.addView(img);
            sublinear.addView(btn);
            linear.addView(sublinear, sublparams);
        }
    }
}

result of programm, green vertical lines are buttons, that i cannot to make wider


共 (1) 个答案

  1. # 1 楼答案

    您的按钮正在使用LayoutParams设置宽度和高度,因此您需要在此处更改此属性(LinearLayout.LayoutParams(widht, height):

     LinearLayout.LayoutParams imageparams = new LinearLayout.LayoutParams(500, 300);
    

    按钮的大小必须更改,因为您正在设置此值

     btn.setLayoutParams(imageparams);