2011-10-19 32 views
0

我一直環顧四周,發現有很多可能的解決方案佈局中的中心一個TextView。但沒有人爲我工作。 我的TextView是在由下面的XML描述一個TableLayout:的TextView layout_gravity不工作程序

<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:id="@+id/schedule_main_holder"> 
    <TableLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:stretchColumns="0" 
     android:id="@+id/schedule_table_entry"> 
    </TableLayout> 
</LinearLayout> 

我正在做的是做一個新的TableRow,然後添加一個TextView和一個ListView吧......但是TextView的有垂直居中。爲此,我在做:

TableRow row = new TableRow(this); 

     TextView tview = new TextView(this); 
     tview.setText("Wednesday"); 
     TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER_VERTICAL); 
     tview.setLayoutParams(layoutParams); 
     row.addView(tview); 

問題是TextView總是在單元格的頂部,而不是在它應該的中間。 我試過混合組合(即使是在另一個響應中描述的FrameLayout方法),我無法讓textview在表格單元中居中。

在此先感謝

回答

1

首先有兩類gravity.I的認爲你使用常規的重力沒有佈局之一。 秒你也可以在xml中創建視圖,然後使用inflatrer然後添加。這給了aswel更清潔的代碼。

編輯: 所以你懶得實際嘗試佈局充氣並聽取意見,這裏是代碼:

main.xml中

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:stretchColumns="0" 
android:id="@+id/schedule_table_entry"> 
</TableLayout> 

myrow.xml

<?xml version="1.0" encoding="utf-8"?> 
<TableRow xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:orientation="vertical"> 
<TextView 
    android:id="@+id/text" 
    android:layout_height="wrap_content" 
    android:layout_width="wrap_content" 
    android:layout_gravity="center" /> 
</TableRow> 

測試活動

public class TestActivity extends Activity { 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    LayoutInflater inflater = getLayoutInflater(); 
    TableRow row = (TableRow) inflater.inflate(R.layout.myrow, null); 
    TextView text = (TextView) row.findViewById(R.id.text); 
    text.setText("I did all your work... smart even"); 

    TableLayout table = (TableLayout) findViewById(R.id.schedule_table_entry); 
    table.addView(row); 
} 
+0

感謝您的回覆,但我已經嘗試了inflater方法,並且layout_gravity被簡單忽略。我確實需要layout_gravity,因爲我希望textview能夠集中在單元格上,而不是文本本身。至少我已經嘗試過setGravity,它不起作用,當textview在xml中定義時,layout_gravity就起作用了。 –

+0

更新的迴應建議。 – Warpzit

+0

感謝您的回覆,我剛剛嘗試過,它的工作原理。我確實嘗試了膨脹方法,但不是在TableRow中,而是直接膨脹了TextView,這可能是問題所在。 –