Android Приложение не реагирует на нажатие кнопки со стрелкой назад - PullRequest
0 голосов
/ 05 августа 2020

Здравствуйте, уважаемые разработчики! Я разработал приложение Android, которое использует Flickr API для отображения любого изображения по запросу пользователя. Я заключительный шаг в развитии. Все выглядит отлично, за исключением случаев, когда вы нажимаете на любое изображение, чтобы развернуть его в подробном представлении, и когда вы щелкаете стрелку возврата на go назад - НЕ отвечает ... Любая помощь будет принята с благодарностью :)

ViewPhotoDetails. java:

package com.example.flickrbrowser;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import androidx.annotation.RequiresApi;

public class ViewPhotoDetailsActivity extends BaseActivity {

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.photo_details);
    activateToolbarWithHomeEnabled();

    Intent intent = getIntent();
    Photo photo = (Photo) intent.getSerializableExtra(PHOTO_TRANSFER);

    TextView photoTitle = (TextView) findViewById(R.id.photo_title);
    photoTitle.setText("Title: " + photo.getTitle());

    TextView photoTags = (TextView) findViewById(R.id.photo_tags);
    photoTags.setText("Tags: " + photo.getTags());

    TextView photoAuthor = (TextView) findViewById(R.id.photo_author);
    photoAuthor.setText(photo.getAuthor());

    ImageView photoImage = (ImageView) findViewById(R.id.photo_image);
    Picasso.with(this).load(photo.getLink())
            .error(R.drawable.placeholder)
            .placeholder(R.drawable.placeholder)
            .into(photoImage);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_photo_details, menu);
    return true;
}

public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return false;
}
}    

photo_details. xml:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:flickr="http://schemas.android.com/apk/res-auto"
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"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.example.flickrbrowser.ViewPhotoDetailsActivity"
tools:showIn="@layout/photo_details">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include
        android:id="@+id/app_bar"
        layout="@layout/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?actionBarSize" />

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="16dp"
        flickr:cardBackgroundColor="?colorPrimary"
        flickr:cardCornerRadius="8dp"
        flickr:cardPreventCornerOverlap="false"
        flickr:contentPaddingTop="16dp"
        flickr:contentPaddingBottom="16dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <ImageView
                    android:id="@+id/photo_image"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginBottom="8dp"
                    android:layout_marginLeft="8dp"
                    android:layout_marginRight="8dp"
                    android:layout_marginTop="8dp"
                    android:scaleType="centerCrop"
                    android:src="@drawable/placeholder" />

                <TextView
                    android:id="@+id/photo_author"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="top|center"
                    android:paddingTop="8dp"
                    android:textColor="@color/flickrSecondaryTextColor"
                    android:textSize="14sp" />

            </FrameLayout>

            <TextView
                android:id="@+id/photo_title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="8dp"
                android:layout_marginTop="8dp"
                android:textColor="@color/flickrPrimaryTextColor"
                android:textSize="14sp" />

            <TextView
                android:id="@+id/photo_tags"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="8dp"
                android:layout_marginTop="8dp"
                android:textColor="@color/flickrPrimaryTextColor"
                android:textSize="10sp" />
        </LinearLayout>
    </androidx.cardview.widget.CardView>
</LinearLayout>
</ScrollView>

Исходный код на GitHub

Пользовательский интерфейс приложения

Ответы [ 3 ]

0 голосов
/ 05 августа 2020

Как сказал @Boken, кнопка назад (также называемая «вверх») - это кнопка меню с идентификатором android.R.id.home, поэтому при нажатии этой кнопки вы можете обрабатывать щелчок следующим образом:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) { 
    //You can also use if-else statements instead of switch (switch is a better option)
        case R.id.action_settings:
            return true;
        case android.R.id.home: //when the back button is clicked
            // handle this action here
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

, если вы хотите вернуться к предыдущему экрану, используйте onBackPressed(), например:

    case android.R.id.home: //when the back button is clicked
        onBackPressed();
        return true;
0 голосов
/ 11 августа 2020

(Более прямой ответ) Не проверял этот пункт меню. Пришлось изменить onOptionsItemSelected (в ViewPhotoDetailsActivity. java) на

public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
    return true;
} else if (id == android.R.id.home) {
    finish();
}
return false;
}
0 голосов
/ 05 августа 2020

Кнопка возврата имеет идентификатор: android.R.id.home. Таким образом, вы можете обработать его как

if (item?.itemId == android.R.id.home) {
    finish()
}

или просто изменить свой

override fun onOptionsItemSelected(item: MenuItem?): Boolean {
    if (item.itemId == R.id.action_settings) {
        // TODO - handle 'settings' click
    }

    return super.onOptionsItemSelected(item)
}

вместо того, чтобы возвращать только true/false, чтобы кнопка home обрабатывалась методом super.

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