Android 从片段获取表格布局

Android 从片段获取表格布局,android,android-fragments,classcastexception,android-tablelayout,Android,Android Fragments,Classcastexception,Android Tablelayout,我创建了一个片段,其UI初始化如下: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/act

我创建了一个片段,其UI初始化如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TableLayout android:id="@+id/table_other"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             >
....<-- The rows are dynamically added although it is initialized with the first row already inserted-->
</TableLayout>
</RelativeLayout>
这将抛出错误:

 AndroidRuntime(1959): FATAL EXCEPTION: main
 AndroidRuntime(1959): java.lang.ClassCastException: android.support.v4.app.NoSaveStateFrameLayout cannot be cast to android.widget.RelativeLayout
AndroidRuntime(1959):   at com.example.newcontactlayout.MainActivity.getTableLayoutFromFragment(MainActivity.java:283)
AndroidRuntime(1959):   at com.example.newcontactlayout.MainActivity.saveContact(MainActivity.java:373)
AndroidRuntime(1959):   at com.example.newcontactlayout.MainActivity.onOptionsItemSelected(MainActivity.java:83)
AndroidRuntime(1959):   at android.app.Activity.onMenuItemSelected(Activity.java:2566)
AndroidRuntime(1959):   at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:372)

如何从片段中获取TableLayout(片段是使用XML添加的)?

tl=(TableLayout)((ViewGroup)f.getView()).findViewById(R.id.table_other)
@Luksprog假设性问题,如果没有id怎么办?在布局中使用现有视图的id(然后从该视图开始移动视图层次结构),或者在目标视图上设置id,即使不需要id。依赖
getView()
在布局中使用精确的结构是危险的,将来可能会失败(正如您在问题中已经看到的)。
 AndroidRuntime(1959): FATAL EXCEPTION: main
 AndroidRuntime(1959): java.lang.ClassCastException: android.support.v4.app.NoSaveStateFrameLayout cannot be cast to android.widget.RelativeLayout
AndroidRuntime(1959):   at com.example.newcontactlayout.MainActivity.getTableLayoutFromFragment(MainActivity.java:283)
AndroidRuntime(1959):   at com.example.newcontactlayout.MainActivity.saveContact(MainActivity.java:373)
AndroidRuntime(1959):   at com.example.newcontactlayout.MainActivity.onOptionsItemSelected(MainActivity.java:83)
AndroidRuntime(1959):   at android.app.Activity.onMenuItemSelected(Activity.java:2566)
AndroidRuntime(1959):   at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:372)