使用按钮打开关闭地图(更改布局)

时间:2016-12-17 19:51:02

标签: java android google-maps button maps

我正在尝试使用按钮打开和关闭地图(更改布局)。

我在MainActivity中有一个按钮,可以打开SecondActivity并设置maps_layout

我在地图上有一个按钮。这会正确切换到另一个布局。

当我想切换回来时,我得到Fatal Exception

我的代码:

public class Game extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mapy();
    }

    public void mapy() {
        setContentView(R.layout.mapy_test);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map_test);
        mapFragment.getMapAsync(this);

        Button changetocam = (Button) findViewById(R.id.changetocam);

        changetocam.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cam();
            }
        });
    }

    public void cam() {
        setContentView(R.layout.ingame_masteroverlay_layout);

        Button changetomap = (Button) findViewById(R.id.changetomap);

        changetomap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mapy();
            }
        });
    }
}

以下是错误日志:

`FATAL EXCEPTION: main Process: auftour.mrorhan.probieren, PID: 2689 android.view.InflateException: Binary XML file line #6: Binary XML file line #6: Error inflating class fragment Caused by: android.view.InflateException: Binary XML file line #6: Error inflating class fragment Caused by: java.lang.IllegalArgumentException: Binary XML file line #6: Duplicate id 0x7f0f010b, tag null, or parent id 0xffffffff with another fragment for com.google.android.gms.maps.SupportMapFragment` 

我认为错误是因为我没有关闭mapy_test布局,因此当我尝试再次连接到地图时,我有双重ID。

2 个答案:

答案 0 :(得分:0)

//尝试这个它对我有用     查看v;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (v != null) {
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null)
            parent.removeView(v);
    }
    try
 {
        v = inflater.inflate(R.layout.mapy_test, container, false);
    } catch (InflateException e) {
        /* map is already there, just return view as it is */
    }
    return v;
}

答案 1 :(得分:0)

所以伙计们,我解决了我的问题。我使用框架和额外的框架containerlayout。如果有人有同样的问题,我可以编写自己的代码。