2017-09-17 158 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沒有方向)。

無論哪種方式,您必須遵守所有佈局只能有一個根的規則。這並不意味着所有的佈局只能有一個視圖,但只要你有多個佈局,你必須找出一個好的盒子把它們全部放入。