2011-09-20 60 views
0

我是Android開發人員(3天前開始),並且在聲明View的佈局時遇到問題。我已到處檢查如何以編程方式設置TextView的頁邊距,到目前爲止,它們都無法工作。當我應用佈局時,TextView總是消失。爲TextView設置邊距使其消失

這裏是我的代碼:

TableLayout tView = (TableLayout)findViewById(R.id.AllDocumentsTable); 
TableRow trView = buildRow(); 

TextView tViewProjTitle = buildCell(); 
tViewProjTitle.setText(doc.project); 

TextView tViewDocTitle = buildCell(); 
tViewDocTitle.setText(doc.document); 

trView.addView(tViewProjTitle); 
trView.addView(tViewDocTitle); 

try { 
     tView.addView(trView, i); 
    } 
catch (Exception e) { 
    Log.e("adding tablerow", e.getMessage()); 
    } 

buildRow()..

private TableRow buildRow(){ 
     TableRow retRow = new TableRow(this); 
     retRow.setBackgroundColor(Color.WHITE); 
     TableLayout.LayoutParams rowLayout = new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, 
       TableLayout.LayoutParams.WRAP_CONTENT); 

     rowLayout.setMargins(2, 2, 2, 2); 
     retRow.setLayoutParams(rowLayout); 
     return retRow; 
} 

buildCell()..

private TextView buildCell(){ 
    TextView retTView = new TextView(this); 

    retTView.setBackgroundColor(Color.WHITE); 
    retTView.setGravity(0); 

    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 
      LinearLayout.LayoutParams.WRAP_CONTENT); 
    params.setMargins(2, 2, 2, 2); 

    retTView.setLayoutParams(params); 
    return retTView; 
} 

我的動態的佈局。

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
     xmlns:android="http://schemas.android.com/apk/res/android" 
     android:orientation="vertical" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:background="#ffffff"> 
    <HorizontalScrollView android:id="@+id/horizontalScrollView1" android:layout_width="wrap_content" android:layout_height="wrap_content"> 
     <LinearLayout 
      xmlns:android="http://schemas.android.com/apk/res/android" 
      android:orientation="vertical" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:background="#ffffff"> 
      <TableLayout android:layout_height="wrap_content" 
       android:id="@+id/AllDocumentsTable" 
       android:layout_width="match_parent" 
       android:background="#ffffff"> 
       <TableRow android:layout_margin="2dp" 
        android:background="#000000"> 
        <TextView android:text="Test Text1." android:layout_margin="2dp" android:background="#ffffff"></TextView> 
        <TextView android:text="Test Text2" android:layout_margin="2dp" android:background="#ffffff"></TextView> 
       </TableRow> 
      </TableLayout>  
     </LinearLayout> 
    </HorizontalScrollView>  
</LinearLayout> 

幫助!!! :)

回答

2

您可以設置頁邊距是這樣的:

LinearLayout.LayoutParams lp=(LinearLayout.LayoutParams)textview.getLayoutParams(); 
    lp.topMargin=10; 
    lp.leftMargin=10; 
+0

啊哈,我的錯誤是,我要*後已經設置TextView的佈局*,我加入的TableRow到TableLayout。在此之後,你的回答,現在它完美地工作!謝謝! –