2017-09-17 160 views
0

因此,这是我的maps_activity.xml文件,当我尝试添加按钮字段时,出现错误Multiple root tags。我必须使用片段布局,因为它在我的Google地图代码中。如何在片段布局上添加按钮?(Google maps Android studio)

<fragment xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/map" 
    android:name="com.google.android.gms.maps.SupportMapFragment" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    /> 

当我尝试添加

<Button 
android:id="@+id/button" 
android:layout_width="146dp" 
android:layout_height="wrap_content" 
android:text="Open Store" /> 

我得到一个错误信息Multiple root tags,该部分之前我尝试添加它,但是,它仍然无法正常工作!

我MapsActivity类,直到onCreate方法

public class MapsActivity extends AppCompatActivity 
     implements OnMapReadyCallback, 
     GoogleApiClient.ConnectionCallbacks, 
     GoogleApiClient.OnConnectionFailedListener, 
     com.google.android.gms.location.LocationListener{ 

    GoogleMap mGoogleMap; 
    SupportMapFragment mapFrag; 
    LocationRequest mLocationRequest; 
    GoogleApiClient mGoogleApiClient; 
    Location mLastLocation; 
    Marker mCurrLocationMarker; 
    Marker marker; 

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

     getSupportActionBar().setTitle("Map Location Activity"); 

     mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); 
     mapFrag.getMapAsync(this); 

    } 

回答

0

每个XML布局文件只能有一个 “根” 的标签。通常这会是某种ViewGroup;常见示例包括LinearLayout,FrameLayout,ConstraintLayoutRelativeLayout

正确的选择取决于你期望的目标是什么。考虑到你只提到了Google地图和Button,所要问的问题是你是否希望这两件事情彼此相邻(或者彼此上下)或者彼此重叠。

如果你想他们是高于/低于对方,选择LinearLayout,写这样的事:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical"> 

    <fragment 
     android:id="@+id/map" 
     android:name="com.google.android.gms.maps.SupportMapFragment" 
     android:layout_width="match_parent" 
     android:layout_height="0dp" 
     android:layout_weight="1"/> 

    <Button 
     android:id="@+id/button" 
     android:layout_width="146dp" 
     android:layout_height="wrap_content" 
     android:text="Open Store"/> 

</LinearLayout> 

相反,如果你希望按钮浮在地图之上,改变LinearLayoutFrameLayout (并删除orientation属性,因为framelayouts没有方向)。

无论哪种方式,您必须遵守所有布局只能有一个根的规则。这并不意味着所有的布局只能有一个视图,但只要你有多个布局,你必须找出一个好的盒子把它们全部放入。