Android - 如何将布局加载到视图中?

时间:2014-01-03 13:04:28

标签: android

似乎没有例子可行。我有一个RelativeLayout:

<View
    android:id="@+id/latest_info_container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
</View>

在活动中:

LayoutInflater inflater = getLayoutInflater();
View latest_info_content = inflater.inflate(R.layout.latest_info, null);
View latest_info_container = (View)findViewById(R.id.latest_info_container);
((ViewGroup)latest_info_container).addView(latest_info_content,0);

应用程序崩溃 - 错误为android.view.View cannot be cast to android.view.ViewGroup。 当我在布局中将<View>更改为<ViewGroup>时,错误为can't instantiate class android.view.ViewGroup

2 个答案:

答案 0 :(得分:1)

尝试用Linear / RelativeLayout替换你的View,它应该有效:

<RelativeLayout
    android:id="@+id/latest_info_container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
</RelativeLayout>

LayoutInflater inflater = getLayoutInflater();
View latest_info_content = inflater.inflate(R.layout.latest_info, null);
RelativeLayout latest_info_container = (RelativeLayout)findViewById(R.id.latest_info_container);
latest_info_container.addView(latest_info_content,0);

答案 1 :(得分:1)

只有ViewGroup可以有孩子。 View不能。