gpt4 book ai didi

java - RecyclerView和CardView实现onClick

转载 作者:行者123 更新时间:2023-11-29 11:29:40 26 4
gpt4 key购买 nike

我有一堆从 mysql 数据库中提取的值,然后使用 RecyclerView 显示在cardview 中。这很好用。

我现在想在拉出的每个项目上实现 onClick,有人可以指出我正确的方向吗?我正在考虑能够单击卡片并打开另一个 View ,其中包含使用 json 从 mysql 中提取的“图像”、“名称”和“发布者”值,问题是我不知道如何传递这些值值到新 Activity ,尤其是从 mysql 中提取的值。

Movies.java

public class Movies extends AppCompatActivity implements RecyclerView.OnScrollChangeListener {

//Creating a List of superheroes
private List<SuperHero> listSuperHeroes;

//Creating Views
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;

//Volley Request Queue
private RequestQueue requestQueue;

//The request counter to send ?page=1, ?page=2 requests
private int requestCount = 1;

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

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

//Initializing Views
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
layoutManager = new GridLayoutManager(this,2);
recyclerView.setLayoutManager(layoutManager);

recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.HORIZONTAL_LIST));
recyclerView.setItemAnimator(new DefaultItemAnimator());

//Initializing our superheroes list
listSuperHeroes = new ArrayList<>();
requestQueue = Volley.newRequestQueue(this);

//Calling method to get data to fetch data
getData();

//Adding an scroll change listener to recyclerview
recyclerView.setOnScrollChangeListener(this);

//initializing our adapter
adapter = new CardAdapter(listSuperHeroes, this);

//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
}

//Add back button to go back
@Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
}

public boolean onSupportNavigateUp(){
finish();
overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
return true;
}

//Request to get json from server we are passing an integer here
//This integer will used to specify the page number for the request ?page = requestcount
//This method would return a JsonArrayRequest that will be added to the request queue
private JsonArrayRequest getDataFromServer(int requestCount) {
//Initializing ProgressBar
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar1);

//Displaying Progressbar
progressBar.setVisibility(View.VISIBLE);
setProgressBarIndeterminateVisibility(true);

//JsonArrayRequest of volley
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigMovies.DATA_URL + String.valueOf(requestCount),
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
//Calling method parseData to parse the json response
parseData(response);
//Hiding the progressbar
progressBar.setVisibility(View.GONE);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.GONE);
//If an error occurs that means end of the list has reached
Toast.makeText(Movies.this, "No More Items Available", Toast.LENGTH_SHORT).show();
}
});

//Returning the request
return jsonArrayRequest;
}

//This method will get data from the web api
private void getData() {
//Adding the method to the queue by calling the method getDataFromServer
requestQueue.add(getDataFromServer(requestCount));
//Incrementing the request counter
requestCount++;
}

//This method will parse json data
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
//Creating the superhero object
SuperHero superHero = new SuperHero();
JSONObject json = null;
try {
//Getting json
json = array.getJSONObject(i);

//Adding data to the superhero object
superHero.setImageUrl(json.getString(ConfigMovies.TAG_IMAGE_URL));
superHero.setName(json.getString(ConfigMovies.TAG_NAME));
superHero.setPublisher(json.getString(ConfigMovies.TAG_PUBLISHER));
} catch (JSONException e) {
e.printStackTrace();
}
//Adding the superhero object to the list
listSuperHeroes.add(superHero);
}

//Notifying the adapter that data has been added or changed
adapter.notifyDataSetChanged();
}

//This method would check that the recyclerview scroll has reached the bottom or not
private boolean isLastItemDisplaying(RecyclerView recyclerView) {
if (recyclerView.getAdapter().getItemCount() != 0) {
int lastVisibleItemPosition = ((GridLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
return true;
}
return false;
}

//Overriden method to detect scrolling
@Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
//Ifscrolled at last then
if (isLastItemDisplaying(recyclerView)) {
//Calling the method getdata again
getData();
}
}
}

CardAdapter.java

public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {

//Imageloader to load image
private ImageLoader imageLoader;
private Context context;

//List to store all superheroes
List<SuperHero> superHeroes;

//Constructor of this class
public CardAdapter(List<SuperHero> superHeroes, Context context){
super();
//Getting all superheroes
this.superHeroes = superHeroes;
this.context = context;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.superheroes_list, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {

//Getting the particular item from the list
SuperHero superHero = superHeroes.get(position);

//Loading image from url
imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
imageLoader.get(superHero.getImageUrl(), ImageLoader.getImageListener(holder.imageView, R.drawable.ic_blank, android.R.drawable.ic_dialog_alert));

//Showing data on the views
holder.imageView.setImageUrl(superHero.getImageUrl(), imageLoader);
holder.textViewName.setText(superHero.getName());
holder.textViewPublisher.setText(superHero.getPublisher());

}

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

class ViewHolder extends RecyclerView.ViewHolder{
//Views
public NetworkImageView imageView;
public TextView textViewName;
public TextView textViewPublisher;

//Initializing Views
public ViewHolder(View itemView) {
super(itemView);
imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewHero);
textViewName = (TextView) itemView.findViewById(R.id.textViewName);
textViewPublisher = (TextView) itemView.findViewById(R.id.textViewPublisher);
}
}
}

Movies.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true" />
<ProgressBar
android:id="@+id/progressBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</LinearLayout>

superheroes_list.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:nestedScrollingEnabled="false"
android:layout_alignParentEnd="true"
android:layout_marginBottom="3dp">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="@dimen/activity_horizontal_margin">
<com.android.volley.toolbox.NetworkImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="@+id/imageViewHero"
android:layout_gravity="center_horizontal" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TableRow>
<TextView
android:text="Name"
android:paddingRight="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/textViewName"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</TableRow>
<TableRow>
<TextView
android:text="Publisher"
android:paddingRight="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/textViewPublisher"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
</TableLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>

最佳答案

  1. 让ViewHolder类实现View.OnClickListener,然后将其移动到CardAdapter类中。
  2. 在 ViewHolder 构造函数中调用 super 之后调用 setOnClickListener(this) ,如下所示:

    public ViewHolder(View itemView) {
    super(itemView);
    itemView.setOnClickListener(this);
    imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewHero);
    textViewName = (TextView) itemView.findViewById(R.id.textViewName);
    textViewPublisher = (TextView) itemView.findViewById(R.id.textViewPublisher);
    }

    @Override
    public void onClick(View view) {
    // here you can get your item by calling getAdapterPosition();
    SuperHero superHero = superHeroes.get(getAdapterPosition());
    }

关于java - RecyclerView和CardView实现onClick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37622252/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com