2015-06-21 128 views
2

我拼命地試圖添加一個ImageView到TableRow,但不知怎的,我不能。我可以添加一個新的TableRow到TableLayout,但是我不能添加任何東西。 我已經嘗試使行無效,或者我插入的視圖,但沒有區別。不能添加視圖到TableRow動態

代碼:

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 

    final View rootView = inflater.inflate(R.layout.page2, 
      container, false); 
    Button soundBtn = (Button) rootView.findViewById(R.id.p2b1); 
    soundBtn.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      LayoutInflater inflater = activity.getLayoutInflater(); 
      TableRow row = (TableRow)inflater.inflate(R.layout.page2, null).findViewById(R.id.p2row9); 
      View child = (View)inflater.inflate(R.layout.dummyview, null); 
      row.addView(child, 0); 
     } 
    }); 
} 

和XML是:

<TableLayout 
    android:id="@+id/p2table" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:stretchColumns="1" > 
    <TableRow 
     android:id="@+id/p2row9" 
     android:layout_width="wrap_content" 
     android:layout_height="200dip" 
     android:paddingTop="10dip"> 
    </TableRow> 
</TableLayout> 

和我dummyview是:

<?xml version="1.0" encoding="utf-8"?> 
     <View xmlns:android="http://schemas.android.com/apk/res/android" 

      android:layout_width="0dp" 
      android:layout_weight="0.3" 
      android:layout_height="1dp" 
      android:gravity="center" 
      android:background="@color/textbody" /> 

任何幫助表示讚賞。

回答

0

在回調onClick中,您不必在第二次膨脹佈局。

TableRow row = (TableRow) inflater.inflate(R.layout.page2, null).findViewById(R.id.p2row9); 

而是直接使用根視圖查找TableRow

TableRow row = (TableRow) rootView.findViewById(R.id.p2row9);