【问题标题】:Why can't I apply margin while adding linearlayout programmatically?为什么我不能在以编程方式添加线性布局时应用边距?
【发布时间】:2014-09-29 21:57:18
【问题描述】:

在这里,我以编程方式在另一个线性布局中添加一个文本视图。但是,即使我设置了边距,我也无法将边距应用于线性布局。

LinearLayout LL = new LinearLayout(TimeTableAdvanced.this);
                    LL.setBackgroundColor(getResources().getColor(R.color.menublue));
                    LL.setOrientation(LinearLayout.VERTICAL);
                    LL.setGravity(Gravity.TOP);
                    LayoutParams LLParams = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);

                    int marginPixel = 3;
                    float density = TimeTableAdvanced.this.getResources().getDisplayMetrics().density;
                    int marginDp = (int)(marginPixel * density);

                    int marginTopPixel = 3;
                    int marginTopDp = (int)(marginTopPixel * density);

                    LLParams.setMargins(marginDp, marginTopDp, marginDp, marginDp);                 
                    LL.setLayoutParams(LLParams);

                    int paddingPixel = 3;
                    int paddingDp = (int)(paddingPixel * density);
                    LL.setPadding(paddingDp,paddingDp,paddingDp,paddingDp);

                    TextView infoheader = new TextView(TimeTableAdvanced.this);
                    infoheader.setText(getResources().getString(R.string.departuretimesfromfirstbusstop));
                    infoheader.setTextColor(getResources().getColor(R.color.white));
                    infoheader.setTextSize(14.0f);
                    LLParams = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);

                    marginPixel = 5;
                    marginDp = (int)(marginPixel * density);

                    LLParams.setMargins(marginDp, 0, 0, 0);                 
                    infoheader.setLayoutParams(LLParams);

                    LL.addView(infoheader);

                    timetablelayout.addView(LL);

【问题讨论】:

    标签: android android-linearlayout margin


    【解决方案1】:

    试试这个,希望它会工作。

    LinearLayout.LayoutParams LLParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    LLParams.setMargins(marginDp, marginTopDp, marginDp, marginDp); 
    

    附言 只是建议将dp转换为像素的方法,试试看:)

    private int dpToPx(int dp) {

        float density = getResources().getDisplayMetrics().density;
    
        return Math.round((float) dp * density);
    

    }

    【讨论】:

    • 试试这个..希望它会工作.. LinearLayout.LayoutParams LLParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); LLParams.setMargins(marginDp, marginTopDp, marginDp, marginDp);
    • 代替 LayoutParams 尝试使用 LinearLayout.LayoutParams
    猜你喜欢
    • 2013-06-14
    • 2016-09-14
    • 1970-01-01
    • 2012-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-12
    • 1970-01-01
    相关资源
    最近更新 更多