在操作栏上按下后退按钮后,RecyclerView不显示

时间:2019-03-13 14:47:59

标签: java android gridview android-recyclerview

您好,我正在构建一个应用程序,其中MainActivity显示某些类别的GridView。单击每个类别时,将打开另一个Activity(GridItemActivity),并带有一些RecyclerView。同样,当单击RecyclerView时,GalleryActivity将打开以显示所选列表的内容(ImageView和TextView)。在清单文件中,我设置了每个活动的父母,如下所示:

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.gridrecycler">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".GalleryActivity">
            <meta-data android:name="android.support.PARENT_ACTIVITY"
                android:value=".GridItemActivity"/>
        </activity>
        <activity android:name=".GridItemActivity" >
            <meta-data android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity"/>
        </activity>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

问题是:

  1. 当我单击GalleryActivity的ActionBar上的后退图标时,GridActivity会正常显示,但随后没有任何内容(我的RecyclerView项未显示)。此外,ActionBar标题也更改为应用程序名称。

  2. 在回收站适配器上,设置onClick侦听器的最佳方法是什么。它应该在onBindViewHolder方法上还是在ViewHolder类中或应该在哪里。如果它在ViewHolder类上,那么请告诉我如何在我的代码中实现它,因为有点丢失了某些东西。

GridItemActivity.java

package com.example.gridrecycler;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;

import java.util.ArrayList;

public class GridItemActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    private ArrayList<String> mNames = new ArrayList<>();

    private int[] images = {
            R.drawable.apples,R.drawable.bakes,R.drawable.banana,R.drawable.craves,
            R.drawable.grapes,R.drawable.orange,R.drawable.pineapple,R.drawable.redgrapes,
            R.drawable.strawberrys,R.drawable.watermelons
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_grid_item);
        //enable back Button
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        Log.d(TAG, "onCreate: started");

        Log.d(TAG, "getIncomingItent: checking for incoming intents");
        if (getIntent().hasExtra("name")){
            Log.d(TAG, "getIncomingItent: found intent extra");

            String categoryName = getIntent().getStringExtra("name");
            setActionBarTitle(categoryName);

            initImageBitmaps();
        }
    }

    private void setActionBarTitle(String title)
    {
        getSupportActionBar().setTitle(title);
    }

    private void initImageBitmaps(){
        Log.d(TAG, "initImageBitmaps: preparing bitmaps");

        mNames.add("Apple");
        mNames.add("Bakes");
        mNames.add("Banana");
        mNames.add("Craves");
        mNames.add("Grapes");
        mNames.add("Oranges");
        mNames.add("Pineapple");
        mNames.add("Pepper");
        mNames.add("Strawberry");
        mNames.add("Watermelon");

        initRecyclerView();
    }

    private void initRecyclerView(){
        Log.d(TAG, "initRecyclerView: init recyclerview");
        RecyclerView recyclerView = findViewById(R.id.recycler_view);
        RecyclerViewAdapter adapter = new RecyclerViewAdapter(this, mNames, images);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
    }
}

RecyclerViewAdapter.java

package com.example.gridrecycler;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
    private static final String TAG = "RecyclerViewAdapter";

    private ArrayList<String> mImageNames = new ArrayList<>();
    private int[] mImages;
    private Context mContext;

    public RecyclerViewAdapter(Context mContext, ArrayList<String> mImageNames, int[] mImages) {
        this.mImageNames = mImageNames;
        this.mImages = mImages;
        this.mContext = mContext;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_listitem, viewGroup, false);
        ViewHolder holder = new ViewHolder(view, mContext, mImages, mImageNames);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, final int i) {
        Log.d(TAG, "onBindViewHolder: called");
        viewHolder.image.setImageResource(mImages[i]);
        viewHolder.imageName.setText(mImageNames.get(i));
        viewHolder.parentLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: clicked on : "+mImageNames.get(i));
                Toast.makeText(mContext, mImageNames.get(i), Toast.LENGTH_SHORT).show();

                Intent intent = new Intent(mContext, GalleryActivity.class);
                intent.putExtra("image_url", mImages[i]);
                intent.putExtra("image_name", mImageNames.get(i));
                mContext.startActivity(intent);
            }
        });
    }

    @Override
    public int getItemCount() {
        return mImageNames.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        ImageView image;
        TextView imageName;
        RelativeLayout parentLayout;
        int[] images;
        ArrayList<String> mImageNames = new ArrayList<>();
        Context context;

        public ViewHolder(@NonNull View itemView, Context context, int[] images, ArrayList<String> mImageNames) {
            super(itemView);
            image = itemView.findViewById(R.id.image);
            imageName = itemView.findViewById(R.id.image_name);
            parentLayout = itemView.findViewById(R.id.parent_layout);

            itemView.setOnClickListener(this);
            this.context = context;
            this.images = images;
        }

        @Override
        public void onClick(View v) {
            //Intent intent = new Intent(mContext, GalleryActivity.class);
            //intent.putExtra("image_url", mImages[getAdapterPosition()]);
            //intent.putExtra("image_name", mImageNames.get(getAdapterPosition()));
            //mContext.startActivity(intent);
        }
    }
}

GalleryActivity.java

package com.example.gridrecycler;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

public class GalleryActivity extends AppCompatActivity {
    private static final String TAG = "GalleryActivity";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gallery);
        Log.d(TAG, "onCreate: started");
        getIncomingIntent();

    }

    private void getIncomingIntent()
    {
        Log.d(TAG, "getIncomingItent: checking for incoming intents");
        if (getIntent().hasExtra("image_url") && getIntent().hasExtra("image_name")){
            Log.d(TAG, "getIncomingItent: found intent extra");

            int imageUrl = getIntent().getIntExtra("image_url", 000);
            String imageName = getIntent().getStringExtra("image_name");
            getSupportActionBar().setTitle(imageName);

            setImage(imageUrl, imageName);
        }
    }

    private void setImage(int imageUrl, String imageName){
        Log.d(TAG, "setImage: setting image url and name to widgets");
        TextView name = findViewById(R.id.image_description);
        name.setText(imageName);

        ImageView image = findViewById(R.id.image);
        image.setImageResource(imageUrl);
    }
}

很抱歉在一个问题中问了太多。预先感谢。

1 个答案:

答案 0 :(得分:0)

对于问题一(1),这解决了问题。

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            return true;
    }

    return super.onOptionsItemSelected(item);
}

对于第二个,这有帮助

public ViewHolder(@NonNull View itemView, Context context, int[] images, ArrayList<String> mImageNames) {
        super(itemView);
        image = itemView.findViewById(R.id.image);
        imageName = itemView.findViewById(R.id.image_name);
        parentLayout = itemView.findViewById(R.id.parent_layout);

        itemView.setOnClickListener(this);
        this.context = context;
        this.images = images;
        this.mImageNames = mImageNames;
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(mContext, GalleryActivity.class);
        intent.putExtra("image_url", mImages[getAdapterPosition()]);
        intent.putExtra("image_name", mImageNames.get(getAdapterPosition()));
        mContext.startActivity(intent);
    }