【问题标题】:Why my button pulls away?为什么我的按钮会拉开?
【发布时间】:2017-12-13 08:05:06
【问题描述】:

当我在水平方向的线性布局中创建按钮时,上边距出现在其中一个上(左)。当我用数字(1000)设置高度时出现。如果我使用 WRAP_CONTENT 设置它,则不会出现此意外边距。

LinearLayout.LayoutParams btnParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 1000, 1.0f);

我附上错误的图片

我的代码是

final Button[] btnTemp = new Button[answers.length];
    final LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.HORIZONTAL);
    layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
    gameL.addView(layout);
    for(int i = 0; i < answers.length; i++) {
        btnTemp[i] = new Button(getApplicationContext());
        btnTemp[i].setText(answers[i]);
        btnTemp[i].setTextColor(Color.parseColor("#ffffff"));
        btnTemp[i].setTextSize(getResources().getDimension(R.dimen.fab_margin));
        btnTemp[i].setPadding(0, 0, 0, 0);
        btnParams.setMargins(0,0,0,0);
        btnTemp[i].setBackgroundResource(R.drawable.round_shape_btn);
        btnTemp[i].setId(listLast);
        if(i != 2) {
            final int finalI = i;
            btnTemp[i].setLayoutParams(btnParams);
            layout.addView(btnTemp[i]);
        } else {
            Timer f = new Timer();
            final int finalI = i;
            f.schedule(new TimerTask() {
                @Override
                public void run() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(btnTemp[0].getWidth(),
                                    1000);
                            params.gravity = Gravity.CENTER;
                            btnTemp[finalI].setLayoutParams(params);
                            gameL.addView(btnTemp[finalI]);
                        }
                    });
                } }, 1000);

        }
}

【问题讨论】:

    标签: android xml button


    【解决方案1】:

    LayoutParams.WRAP_PARENT总是根据ParentView调整自己,如果你想手动设置高度,那么尝试从dimens.xml文件中获取它

    context.getResources.getDimens(R.dimen.value);
    

    【讨论】:

    • 所以我必须写 LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(btnTemp[0].getWidth(), Math.round(getResources().getDimension(R.dimen.height_button)));但它不起作用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    • 2019-09-07
    • 2020-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多