我不知道如何为这个rec​​yclerView制作一个点击监听器

时间:2017-08-19 03:49:23

标签: java android android-fragments

我遇到了听众的问题,我尝试了一切,但仍然没有工作。

RecyclerView在片段中,因为我使用的是导航抽屉活动,在RecyclerView的项目中我也有一个按钮,但是我想让项目中的点击监听器从标题中获取文本(项目的名称)。

这里我将把代码与我拥有的监听器(适配器,主要活动和片段的类)放在一起。

这是peliculas_mainAdapter:

package com.squaresoftware.mirapelis.adapters;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.toolbox.NetworkImageView;
import com.squaresoftware.mirapelis.Datasets.peliculas_main;
import com.squaresoftware.mirapelis.R;
import com.squaresoftware.mirapelis.Utils.NetworkController;

import java.util.List;

/**
 * Created by carrera on 14/08/17.
 */

public class peliculas_mainAdapter extends RecyclerView.Adapter<peliculas_mainAdapter.MyViewHolder> {





private List<peliculas_main> feedsList;
private Context context;
private LayoutInflater inflater;


    public peliculas_mainAdapter(Context context, List<peliculas_main> feedsList) {

        this.context = context;
        this.feedsList = feedsList;
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View rootView = inflater.inflate(R.layout.item_lst_peliculas, parent, false);
        return new MyViewHolder(rootView);
        }

@Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
         peliculas_main feeds = feedsList.get(position);
        //Pass the values of feeds object to Views
        holder.title.setText(feeds.getTitle());
        holder.content.setText(feeds.getCategoria());
        holder.imageview.setImageUrl(feeds.getImage(), NetworkController.getInstance(context).getImageLoader());

        }

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



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

    public TextView content, title;
    public NetworkImageView imageview;
    public Button btn_accion;



    public MyViewHolder(View itemView) {
        super(itemView);
        title = (TextView) itemView.findViewById(R.id.name);
        content = (TextView) itemView.findViewById(R.id.categoria);
        btn_accion = (Button)itemView.findViewById(R.id.btn_go);
        // Volley's NetworkImageView which will load Image from URL
        imageview = (NetworkImageView) itemView.findViewById(R.id.thumbnail);
        itemView.setOnClickListener(this);


    }

        @Override
        public void onClick(View v) {
            Toast.makeText(context, "lol", Toast.LENGTH_SHORT);
        }
    }
}

这是片段(Peliculas)的类:

package layout;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;

import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;

import java.util.ArrayList;
import java.util.List;

import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.squaresoftware.mirapelis.Datasets.peliculas_main;
import com.squaresoftware.mirapelis.R;
import com.squaresoftware.mirapelis.Utils.NetworkController;
import com.squaresoftware.mirapelis.adapters.peliculas_mainAdapter;

import org.json.JSONArray;
import org.json.JSONObject;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link Peliculas.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link Peliculas#newInstance} factory method to
 * create an instance of this fragment.
 */
public class Peliculas extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    RequestQueue queue;
    String url = "http://pruebaswsp.000webhostapp.com/json/AllMoviesResolver.php";
    RecyclerView recyclerView;
    List<peliculas_main> feedsList = new ArrayList<peliculas_main>();
    peliculas_mainAdapter adapter;
    static String MovieTitle;
    View view2;



    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public Peliculas() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment Peliculas.
     */
    // TODO: Rename and change types and number of parameters
    public static Peliculas newInstance(String param1, String param2) {
        Peliculas fragment = new Peliculas();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_peliculas, container, false);
        view2 = view;
        //Initialize RecyclerView
        recyclerView = (RecyclerView) view.findViewById(R.id.lst_peliculas_main);
        adapter = new peliculas_mainAdapter(getActivity(), feedsList);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        recyclerView.setAdapter(adapter);
        //Getting Instance of Volley Request Queue
        queue = NetworkController.getInstance(getActivity()).getRequestQueue();
        //Volley's inbuilt class to make Json array request
        JsonArrayRequest newsReq = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {

                for (int i = 0; i < response.length(); i++) {
                    try {

                        JSONObject obj = response.getJSONObject(i);
                        peliculas_main feeds = new peliculas_main(obj.getString("Title"), obj.getString("Categoria"), obj.getString("Image"));

                        // adding movie to movies array
                        feedsList.add(feeds);

                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    } finally {
                        //Notify adapter about data changes
                        adapter.notifyItemChanged(i);
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                System.out.println(error.getMessage());
            }
        });
        //Adding JsonArrayRequest to Request Queue
        queue.add(newsReq);







                return view;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
    public static String getVariable()
    {
        String CategTrim = MovieTitle.replaceAll("\\s+","%20");
        return CategTrim;
    }



}

以下是MainActivity:

package com.squaresoftware.mirapelis;

import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.Toast;

import layout.Busqueda;
import layout.Categorias;
import layout.Configuracion;
import layout.Peliculas;

import static com.squaresoftware.mirapelis.R.layout.activity_main;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, Peliculas.OnFragmentInteractionListener, Categorias.OnFragmentInteractionListener, Configuracion.OnFragmentInteractionListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction().replace(R.id.Contenedor, new Peliculas()).commit();
        }


        /*FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "LOL", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });*/

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        navigationView.setCheckedItem(R.id.nav_peliculas);
        getSupportActionBar().setTitle("Peliculas");

    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }



    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {


        int id = item.getItemId();
        Fragment fragment = null;
        boolean FragmentoSeleccionado = false;

        if (id == R.id.nav_peliculas) {
                fragment = new Peliculas();
                FragmentoSeleccionado = true;
        } else if (id == R.id.nav_categorias) {
            fragment = new Categorias();
            FragmentoSeleccionado = true;
        } else if (id ==  R.id.nav_buscar){
            fragment = new Busqueda();
            FragmentoSeleccionado = true;
        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_config) {
            fragment = new Configuracion();
            FragmentoSeleccionado = true;
        }

        if(FragmentoSeleccionado){
            getSupportFragmentManager().beginTransaction().replace(R.id.Contenedor, fragment).commit();

            item.setChecked(true);
            getSupportActionBar().setTitle(item.getTitle());
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }
}

以下是RecyclerView的项目:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="8dp"
    android:id="@+id/lay_lst_peliculas">

    <com.android.volley.toolbox.NetworkImageView
        android:id="@+id/thumbnail"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_alignParentLeft="true"
        android:layout_marginRight="8dp" />

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/thumbnail"
        android:layout_toRightOf="@+id/thumbnail"
        android:clickable="false"
        android:fontFamily="sans-serif-condensed"
        android:textColor="#181818"
        android:textSize="15dp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/categoria"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"


        android:fontFamily="sans-serif-condensed"

        android:textColor="#484848"
        android:textSize="13dp"
        android:textStyle="bold"
        android:layout_centerVertical="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_toEndOf="@+id/thumbnail"
        android:layout_toRightOf="@+id/thumbnail" />

    <Button
        android:id="@+id/btn_go"
        android:layout_width="50dp"
        android:layout_height="40dp"
        android:layout_alignBottom="@+id/thumbnail"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:text="Ver" />


</RelativeLayout>

我是Java的新手,我不得不说这很难。

0 个答案:

没有答案