这是我的 maps_activity.xml
文件,当我尝试添加按钮字段时,出现错误多个根标签
。
<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" />
我收到一条错误消息多个根标签
。
我的 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);
}
谢谢!
最佳答案
每个 XML 布局文件只能有一个“根”标签。通常这将是某种ViewGroup
;常见示例包括 LinearLayout
、FrameLayout
、ConstraintLayout
和 RelativeLayout
。
正确的选择取决于您的期望目标是什么。考虑到您只提到了 Google map 和 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>
如果您希望按钮 float 在 map 顶部,请将 LinearLayout
更改为 FrameLayout
(并删除 orientation
属性,因为框架布局没有方向)。
无论哪种方式,您都必须遵守所有布局只能有一个根的规则。这并不意味着所有布局只能有一个 View ,但一旦你有多个 View ,你就必须找到一个好的盒子来将它们全部放入。
关于android - 如何在 fragment 布局上添加按钮?(Google map Android studio),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46260887/