Мое приложение не открывается после интеграции с Google Maps - PullRequest
0 голосов
/ 07 февраля 2019

Я создал приложение, которое в основном показывает 3 разных фрагмента с меню «Нижняя навигация» внизу.Я хочу открыть новое действие с плавающей кнопкой действия, которое содержит карту Google, но, к сожалению, приложение закрывается, если я пытаюсь его запустить.

Мой XML-файл MainActivity:

<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"
tools:context=".MainActivity">

<FrameLayout
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@+id/mapbutton">

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/floatingActionButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:clickable="true"
        app:srcCompat="@drawable/ic_public"
        tools:ignore="VectorDrawableCompat" />
</FrameLayout>

<android.support.design.widget.BottomNavigationView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    app:menu="@menu/bottom_navigation"
    android:id="@+id/mapbutton"/>

XML-файл моей активности в Google Maps:

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

Это мой основной Java-файл:

public class MainActivity extends AppCompatActivity {

private FloatingActionButton button;

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

    BottomNavigationView bottomNav = findViewById(R.id.mapbutton);
    bottomNav.setOnNavigationItemSelectedListener(navListener);

    //I added this if statement to keep the selected fragment when rotating the device
    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                new BlogActivity()).commit();
    }

    button = findViewById(R.id.mapbutton);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openTourActivity();
        }
    });
}

public void openTourActivity(){

    Intent intent = new Intent(this, TourActivity.class);
    startActivity(intent);
}

private BottomNavigationView.OnNavigationItemSelectedListener navListener =
        new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                Fragment selectedFragment = null;

                switch (item.getItemId()) {
                    case R.id.nav_blog:
                        selectedFragment = new BlogActivity();
                        break;
                    case R.id.nav_explore:
                        selectedFragment = new ExporeActivity();
                        break;
                    case R.id.nav_user:
                        selectedFragment = new UserActivity();
                        break;
                }

                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        selectedFragment).commit();

                return true;
            }
        };
}

Это действие в Google Map.Я ничего не изменил.Я просто скопировал и попытался запустить его.

public class TourActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tour);
    // 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);
}


/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Add a marker in Sydney and move the camera
    LatLng sydney = new LatLng(-34, 151);
    mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}}

Мой Logcat говорит:

 Caused by: java.lang.ClassCastException: android.support.design.widget.FloatingActionButton cannot be cast to android.support.design.widget.BottomNavigationView

Мне удалось построить нечто подобное некоторое время назад, и это сработало, нона этот раз я борюсь.Приложение запускается, если я установил «Активность в Картах» в качестве «Активности», но мне нужно, чтобы она была запущена с «Основным действием».

С нетерпением ждем вашей помощи и ответов.

1 Ответ

0 голосов
/ 07 февраля 2019

Эта строка неверна:

BottomNavigationView bottomNav = findViewById(R.id.mapbutton);
....
....
button = findViewById(R.id.mapbutton);

Заменить mapbutton на BottomNavigationView Идентификатор.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...