添加地图活动(FragmentActivity)到导航抽屉(Fragment)。

huangapple go评论87阅读模式
英文:

adding a MapActivity (FragmentActivity) to Navigation Drawers (Fragment)

问题

以下是翻译好的内容:

我正在尝试在Android Studio中学习编码,但在处理活动时遇到了问题。

我有一个谷歌地图的代码,我想要将其添加到导航抽屉中,但我不能这样做,因为错误总是显示“MapsActivity无法转换为androidx.fragment.app.Fragment”。

这是我的 MapActivity.java

package ***.***.***.ui.map;
import androidx.fragment.app.FragmentActivity;
import android.annotation.SuppressLint;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.WindowManager;
import android.widget.TextView;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;

import java.io.IOException;
import java.util.List;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    // ... 这里是你的代码 ...
}

以及 activity_maps.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    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="match_parent"
        tools:context=".MapsActivity" />

    <!-- ... 其他布局 ... -->

</RelativeLayout>

还有 MainActivity.java

package ***.***.***;

import android.os.Bundle;
import android.view.View;
import android.view.Menu;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.navigation.NavigationView;

import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

public class MainActivity extends AppCompatActivity {

    // ... 这里是你的代码 ...
}

希望这对你有所帮助,让代码能够正常工作,无需重新编写全部代码。

英文:

I am trying to learn coding in Android Studio but I am having trouble with the activities.

I have a google map code that I was to add to the navigation drawer but I can't because the error always says MapsActivity cannot be cast to androidx.fragment.app.Fragment

here is my MapActivity.Java

package ***.***.***.ui.map;
import androidx.fragment.app.FragmentActivity;
import android.annotation.SuppressLint;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.WindowManager;
import android.widget.TextView;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;

import java.io.IOException;
import java.util.List;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private Object LocationServices;
    GoogleMap mMap;
    private GoogleMap.OnCameraIdleListener onCameraIdleListener;
    private TextView resutText;

    @Override
    public void onResume() {
        super.onResume();
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(***.***.***.R.id.map);
        mapFragment.getMapAsync(this);
        resutText = (TextView) findViewById(***.***.***.R.id.dragg_result);
        configureCameraIdle();
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setOnCameraIdleListener(onCameraIdleListener);
        googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        String locationProvider = LocationManager.NETWORK_PROVIDER;
        @SuppressLint(&quot;MissingPermission&quot;) android.location.Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
        double userLat = lastKnownLocation.getLatitude();
        double userLong = lastKnownLocation.getLongitude();
        LatLng user = new LatLng(userLat, userLong);
        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(userLat, userLong), 16.0f));
    }
    private void configureCameraIdle() {
        onCameraIdleListener = new GoogleMap.OnCameraIdleListener() {
            @Override
            public void onCameraIdle() {

                LatLng latLng = mMap.getCameraPosition().target;
                Geocoder geocoder = new Geocoder(MapsActivity.this);

                try {
                    List&lt;Address&gt; addressList = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
                    if (addressList != null &amp;&amp; addressList.size() &gt; 0) {
                        String locality = addressList.get(0).getAddressLine(0);
                        String country = addressList.get(0).getCountryName();
                        if (!locality.isEmpty() &amp;&amp; !country.isEmpty())
                            resutText.setText(locality + &quot;  &quot; + country);
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        };
    }

    protected void setStatusBarTranslucent(boolean makeTranslucent) {
        if (makeTranslucent) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        } else {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

}

and the activity_maps.xml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;
    android:orientation=&quot;vertical&quot;&gt;

    &lt;fragment
        android:id=&quot;@+id/map&quot;
        android:name=&quot;com.google.android.gms.maps.SupportMapFragment&quot;
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;match_parent&quot;
        tools:context=&quot;.MapsActivity&quot; /&gt;

    &lt;ImageView
        android:id=&quot;@+id/imageView&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:layout_alignParentStart=&quot;true&quot;
        android:layout_alignParentTop=&quot;true&quot;
        android:layout_alignParentEnd=&quot;true&quot;
        android:layout_alignParentBottom=&quot;true&quot;
        android:layout_marginStart=&quot;172dp&quot;
        android:layout_marginTop=&quot;310dp&quot;
        android:layout_marginEnd=&quot;172dp&quot;
        android:layout_marginBottom=&quot;356dp&quot;
        android:adjustViewBounds=&quot;true&quot;
        android:maxWidth=&quot;65dp&quot;
        android:maxHeight=&quot;65dp&quot;
        android:src=&quot;@drawable/car_pin&quot; /&gt;
    &lt;!-- Implementation of find my location button --&gt;

    &lt;TextView
        android:id=&quot;@+id/dragg_result&quot;
        android:layout_width=&quot;260dp&quot;
        android:layout_height=&quot;84dp&quot;
        android:layout_alignParentStart=&quot;true&quot;
        android:layout_alignParentTop=&quot;true&quot;
        android:layout_alignParentEnd=&quot;true&quot;
        android:layout_alignParentBottom=&quot;true&quot;
        android:layout_marginStart=&quot;75dp&quot;
        android:layout_marginTop=&quot;74dp&quot;
        android:layout_marginEnd=&quot;75dp&quot;
        android:layout_marginBottom=&quot;572dp&quot;
        android:text=&quot;TextView&quot; /&gt;

    &lt;fragment
        android:id=&quot;@+id/nav_host_fragment&quot;
        android:name=&quot;androidx.navigation.fragment.NavHostFragment&quot;
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;match_parent&quot;
        app:defaultNavHost=&quot;true&quot;
        app:layout_constraintLeft_toLeftOf=&quot;parent&quot;
        app:layout_constraintRight_toRightOf=&quot;parent&quot;
        app:layout_constraintTop_toTopOf=&quot;parent&quot;
        app:navGraph=&quot;@navigation/mobile_navigation&quot; /&gt;



&lt;/RelativeLayout&gt;

Also the MainActivity.java

package ***.***.***;

import android.os.Bundle;
import android.view.View;
import android.view.Menu;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.navigation.NavigationView;

import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

public class MainActivity extends AppCompatActivity {

    private AppBarConfiguration mAppBarConfiguration;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, &quot;Replace with your own action&quot;, Snackbar.LENGTH_LONG)
                        .setAction(&quot;Action&quot;, null).show();
            }
        });
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow)
                .setDrawerLayout(drawer)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }

}

What can I do to make it work without redoing all of the code, thanks in advance.

答案1

得分: 0

我不太确定,但我认为您需要将您的```&lt;framgent&gt;```放在xml文件中的```&lt;FrameLayout&gt;```中,就像这样:

```xml
&lt;FrameLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;&gt;

    &lt;fragment
        android:id=&quot;@+id/mapfragment&quot;
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;match_parent&quot;
        class=&quot;com.google.android.gms.maps.MapFragment&quot;/&gt;

&lt;!-- other components --&gt;

   &lt;fragment
        android:id=&quot;@+id/nav_host_fragment&quot;
        android:name=&quot;androidx.navigation.fragment.NavHostFragment&quot;
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;match_parent&quot;
        app:defaultNavHost=&quot;true&quot;
        app:layout_constraintLeft_toLeftOf=&quot;parent&quot;
        app:layout_constraintRight_toRightOf=&quot;parent&quot;
        app:layout_constraintTop_toTopOf=&quot;parent&quot;
        app:navGraph=&quot;@navigation/mobile_navigation&quot; /&gt;
&lt;/FrameLayout&gt;

有可能是您的导入不正确。如果您在Java类中导入android.support.v4.app.FragmentActivity而不是androidx.fragment.app.FragmentActivity,是否有效?我认为错误可能出现在导入上。


<details>
<summary>英文:</summary>

I am not quite sure, but I think you have to put your ```&lt;framgent&gt;``` inside a ```&lt;FramgeLayout&gt;``` in your xml file like this:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

&lt;fragment
    android:id=&quot;@+id/mapfragment&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;
    class=&quot;com.google.android.gms.maps.MapFragment&quot;/&gt;

<!-- other components -->

<fragment
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="@navigation/mobile_navigation" />
</FrameLayout>


it is possible that your imports are wrong. Does it work if you import this in your java class ```android.support.v4.app.FragmentActivity``` instead of ```androidx.fragment.app.FragmentActivity```? I think the error is in the imports than

</details>



huangapple
  • 本文由 发表于 2020年8月23日 14:30:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/63544071.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定