生成的ToggleButtons动态保证金

时间:2016-02-22 10:37:59

标签: android margin togglebutton

我动态生成了一些ToggleButtons,但我没有实现设置上边距以避免按钮在它们之间加入。

我的代码是下一个,我做错了什么?

private void generateToggleButton(){

    RelativeLayout.LayoutParams lvg = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, R.dimen.tv_et_standart_small);
    lvg.height = R.dimen.tv_et_standart_small;
    lvg.width = RelativeLayout.LayoutParams.MATCH_PARENT;
    lvg.setMargins(0, R.dimen.dp8, 0 ,0);


    for(int e = 0; e < new_exp_Especies.size(); e++){
        final int position = e;
        ToggleButton tb = new ToggleButton(this);

        tb.setBackgroundDrawable(getResources().getDrawable(R.drawable.customshape_orange_red));
        tb.setText(new_exp_Especies.get(position).EspecieDesc);
        tb.setTextOff(new_exp_Especies.get(position).EspecieDesc);
        tb.setTextOn(new_exp_Especies.get(position).EspecieDesc);
        tb.setTextSize(12);
        tb.setGravity(Gravity.CENTER);
        tb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    buttonView.setBackgroundDrawable(getResources().getDrawable(R.drawable.customshape_green));
                    new_exp_Especies.get(position).setValue(1);
                } else {
                    buttonView.setBackgroundDrawable(getResources().getDrawable(R.drawable.customshape_orange_red));
                    new_exp_Especies.get(position).setValue(0);
                }
            }
        });
        tb.setLayoutParams(lvg);

        ll_tbt_especie.addView(tb);
    }

}

1 个答案:

答案 0 :(得分:0)

经过多次尝试,最后,我用以下方法解决了问题:

final LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, getResources().getDimensionPixelOffset(R.dimen.tv_et_standart_small));
lparams.gravity = Gravity.CENTER;
lparams.topMargin = getResources().getDimensionPixelOffset(R.dimen.dp8);