2014-09-29 84 views
-1

這裏我在另一個線性佈局中以編程方式在一個線性佈局中添加一個textview。但是,即使設置了邊界,我也無法將邊距應用於我的線性佈局。爲什麼我不能以編程方式添加linearlayout時應用邊距?

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); 

回答

1

試試這個,希望它能起作用。

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

PS 只是建議方法DP轉換爲像素,試試:)

私人詮釋dpToPx(INT DP){

float density = getResources().getDisplayMetrics().density; 

    return Math.round((float) dp * density); 

}

+0

它沒不行。 – 2014-09-29 12:15:13

+0

嘗試此..hope它將工作.. LinearLayout.LayoutParams LLParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT); LLParams.setMargins(marginDp,marginTopDp,marginDp,marginDp); – Prince 2014-09-29 12:23:35

+0

而不是LayoutParams嘗試使用LinearLayout.LayoutParams – Prince 2014-09-29 12:24:52

相關問題