【问题标题】:How to change Parent Activity layout from Child Activity如何从子活动更改父活动布局
【发布时间】:2023-04-01 06:35:01
【问题描述】:

我有一个全屏显示 Google 地图的活动。

我有一个扩展 MapsActivity 的子活动。

当我从 Parent 扩展 child 时,它会在整个屏幕上显示 Map

Child Activity 中,我需要在顶部添加地图,在底部添加列表视图,这将在Child Activity Layout 中实现。

我尝试这样做,但它给了我以下错误消息,

Caused by: java.lang.IllegalStateException: 指定的孩子 已经有了父母。您必须在孩子的父母上调用 removeView() 首先。

public class PlacesListActivity extends GoogleMapsActivity{

    View parentFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_google_map);

        parentFragment= findViewById(R.id.g_map);

        LinearLayout linearLayout= new LinearLayout(this);
            linearLayout.setOrientation(LinearLayout.VERTICAL);
            linearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));

        linearLayout.addView(parentFragment);

在上面的代码中,我没有使用ChildActivity Layout,但是如果我使用它,它并没有得到Parent Activity的元素。

【问题讨论】:

  • 正如错误所说,parentFragment 我会假设您的地图已经设置在父级上。您可能必须创建一个新地图并将其添加到您的线性布局中。这都是一个假设。您可能必须发布您的 xml 文件,以便我们更清楚地看到它。

标签: android android-layout android-fragments android-fragmentactivity


【解决方案1】:

您可以使用以下方法更改父级的视图:

View viewToBeRemoved= view.findViewById(R.id.view_to_be_removed);
View parent = viewToBeRemoved.getParent();
if (parent != null) {
    ((ViewGroup) parent).removeView(viewToBeRemoved);
}
parent.addView(modifiedViewToBeAdded);

但不推荐这样做。

推荐的方法是在你的一半活动中使用地图片段,并在活动的剩余部分显示列表。

请查看How to use MapFragment这个帖子

【讨论】:

    猜你喜欢
    • 2014-04-04
    • 2012-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多