Setting margin to TextView makes it disappear
I'm a beginner in Android devt (started 3 days ago) and have a problem declaring a View's Layout. I have checked everywhere on how to set a TextView's margins programatically and so far, none of them work. The TextView always disappears when I apply the Layout.
Here's my code:
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;
}
My Activity's layout.
<?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:bac开发者_Go百科kground="#ffffff"></TextView>
<TextView android:text="Test Text2" android:layout_margin="2dp" android:background="#ffffff"></TextView>
</TableRow>
</TableLayout>
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
Help!!! :)
you can set the margins like this:
LinearLayout.LayoutParams lp=(LinearLayout.LayoutParams)textview.getLayoutParams();
lp.topMargin=10;
lp.leftMargin=10;
精彩评论