如何通过 CustomAdapter 将保存在 drawable 文件夹中的图像传递给 NewActivity
How to pass images saved in drawable folder via CustomAdapter to NewActivity
如何将 RecyclerView
中的图像数组传递给 NewActivity.java
?我不是说来自 row.xml
的图像 - 我想要一组不同于 row.xml
到 NewActivity
的新图像。我将图像保存在可绘制文件夹中。
我下面的试验是相关的类和activity。
文件String.xml
<string-array name="array_titles">
<item>"<![CDATA[[01] general focus]]>"</item>
<item>"<![CDATA[[02] general view for delibration]]>"</item>
</string-array>
<string-array name="array_lyrics">
<item>"<![CDATA[general]]>"</item>
<item>"<![CDATA[ General ]]>"</item>
<item>"<![CDATA[ General ]]>"</item>
<item>"<![CDATA[ General ]]>"</item>
</string-array>
<string-array name="newbrandDesc">
<item>"<![CDATA[ description here ]]>"</item>
<item>"<![CDATA[ description here ]]>"</item>
<item>"<![CDATA[ description here ]]>"</item>
<item>"<![CDATA[ here ]]>"</item>
</string-array>
文件MainActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<View
android:id="@+id/viewerage"
android:background="#01312D"
android:layout_width="match_parent"
android:layout_height="5dp" />
<!-- First Row-->
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="70dp"
android:layout_below="@id/viewerage"
style="@style/scrollbar_shape_style"
android:id="@+id/recyclerview">
</androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>
文件MainActivity.java
public class MainActivity extends AppCompatActivity {
private String TAG = "MainActivity ----- ; ";
private static MediaPlayer player;
String soundfile;
TextView mDetailTv1;
RecyclerView mRecyclerview;
MyAdapter myAdapter;
int [] MusicFile;
List<String> title, newDesc, description;
int[] icon;
ArrayList<Model> arrayList = new ArrayList<Model>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("Intro Songs");
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Listview icons for song titles in position
icon = new int[]{R.drawable.song, R.drawable.song, R.drawable.song, };
mRecyclerview = findViewById(R.id.recyclerview);
mRecyclerview.setLayoutManager(new LinearLayoutManager(this));
title = Arrays.asList(getResources().getStringArray(R.array.array_titles));
// listview descriptions for songs in position
description = Arrays.asList(getResources().getStringArray(R.array.array_lyrics));
// listview NewDescriptions (NewActivity) for songs in position
newDesc = Arrays.asList(getResources().getStringArray(R.array.newbrandDesc));
// listview soundfile file for songs in position
MusicFile = new int[] {R.raw.wex_1, R.raw.wex_2, R.raw.wex_3, , };
for (int i = 0; i< title.size(); i++) {
Model model = new Model(title.get(i), description.get(i), newDesc.get(i), icon[i], MusicFile[i]);
// Bind all strings in an array
arrayList.add(model);
}
// Pass result to listview class
myAdapter = new MyAdapter(this, arrayList);
// Bind the adapter to the listview class
mRecyclerview.setAdapter(myAdapter);
}
@Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainActivity.this.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
myAdapter.getFilter().filter(query);
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
myAdapter.getFilter().filter(newText);
return false;
}
});
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Toast.makeText(this, "Favorites Selected", Toast.LENGTH_SHORT).show();
startActivity(new Intent(this, FavoritesActivity.class));
return true;
// Do more funtionality here
}
return super.onOptionsItemSelected(item);
}
}
文件MyAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyHolder> implements Filterable {
Context mContext;
ArrayList<Model> models, filterList; // This array list create a list of array
// which parameter define in our class
CustomFilter filter;
public MyAdapter(Context context, ArrayList<Model> models) {
this.mContext = context;
this.models = models;
this.filterList = models;
}
@NonNull
@Override
public MyHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row, null); // This line inflate our row
return new MyHolder(view); // This will return our view to holder class
}
@Override
public void onBindViewHolder(@NonNull final MyHolder myHolder, int i) {
myHolder.mTitle.setText(models.get(i).getTitle()); // Here is position
myHolder.mDesc.setText(models.get(i).getDesc());
myHolder.mImageView.setImageResource(models.get(i).getIcon()); // Here we used an image resource
myHolder.setItemCLickListener(new ItemClickListener() {
@Override
public void onItemClickListener(View v, int position) {
String gTitle = models.get(position).getTitle();
String gDesc = models.get(position).getDesc();
BitmapDrawable bitmapDrawable = (BitmapDrawable)myHolder.mImageView.getDrawable();
Bitmap bitmap = bitmapDrawable.getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] bytes = stream.toByteArray();
//get our data with intent
Intent intent = new Intent(mContext, NewActivity.class);
intent.putExtra("actionBarTitle", models.get(position).getTitle());
intent.putExtra("brandNewDesc", models.get(position).getBrandNewDesc());
intent.putExtra("soundfile", models.get(position).getSoundfile());
intent.putExtra("iImage", bytes);
mContext.startActivity(intent);
return;
}
});
}
@Override
public int getItemCount() {
return models.size();
}
@Override
public Filter getFilter() {
if (filter == null) {
filter = new CustomFilter(filterList, this);
}
return filter;
}
}
文件MyHolder.java
public class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView mImageView;
TextView mTitle, mDesc;
ItemClickListener itemCLickListener;
MyHolder(@NonNull View itemView) {
super(itemView);
this.mImageView = itemView.findViewById(R.id.mainIcon);
this.mTitle = itemView.findViewById(R.id.mainTitle);
this.mDesc = itemView.findViewById(R.id.mainDesc);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
this.itemCLickListener.onItemClickListener(v, getLayoutPosition());
}
public void setItemCLickListener(ItemClickListener ic) {
this.itemCLickListener = ic;
}
}
文件CustomFilter.java
private ArrayList<Model> filterList;
private MyAdapter adapter;
public CustomFilter(ArrayList<Model> filterList, MyAdapter adapter) {
this.filterList = filterList;
this.adapter = adapter;
}
@Override
protected FilterResults performFiltering(CharSequence constraints) {
FilterResults filterResults = new FilterResults();
if (constraints != null && constraints.length() > 0) {
constraints = constraints.toString().toUpperCase();
ArrayList<Model> filterModels = new ArrayList<>();
for (int i = 0; i < filterList.size(); i++) {
if (filterList.get(i).getTitle().toUpperCase().contains(constraints)) {
filterModels.add(filterList.get(i));
}
}
filterResults.count = filterModels.size();
filterResults.values = filterModels;
}
else {
filterResults.count = filterList.size();
filterResults.values = filterList;
}
return filterResults;
}
@Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
adapter.models = (ArrayList<Model>) filterResults.values;
adapter.notifyDataSetChanged();
}
}
文件ItemClickListener.java-界面
public interface ItemClickListener {
void onItemClickListener(View v, int position);
}
public class NewActivity extends AppCompatActivity {
private String TAG = "NewActivity ----- ; ";
// Store instance variables
private String title;
private int page;
TextView mBrandNewDesc;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Keeps Android screen on while reading through
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
ActionBar actionBar = getSupportActionBar();
mBrandNewDesc = findViewById(R.id.textView);
// Get data from previous activity when item of activity is clicked using intent
Intent intent = getIntent();
String mActionBarTitle = intent.getStringExtra("actionBarTitle");
String newDescription = intent.getStringExtra("brandNewDesc");
// setctionBar Title
actionBar.setTitle(mActionBarTitle);
// Get text in text textView
mBrandNewDesc.setText(Html.fromHtml(newDescription));
// OK, we are done. Let’s run the project
}
@Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
}
而不是 drawable>bitmap>byteArray
发送可绘制资源 ID,如下面的代码更改了 onBindViewHolder
@Override
public void onBindViewHolder(@NonNull final MyHolder myHolder, int i) {
myHolder.mTitle.setText(models.get(i).getTitle()); //here is position
myHolder.mDesc.setText(models.get(i).getDesc());
myHolder.mImageView.setImageResource(models.get(i).getIcon()); // here we used imge resource
myHolder.setItemCLickListener(new ItemClickListener() {
@Override
public void onItemClickListener(View v, int position) {
String gTitle = models.get(position).getTitle();
String gDesc = models.get(position).getDesc();
int imageId = models.get(position).getIcon();
//get our data with the intent
Intent intent = new Intent(mContext, NewActivity.class);
intent.putExtra("actionBarTitle", models.get(position).getTitle());
intent.putExtra("brandNewDesc", models.get(position).getBrandNewDesc());
intent.putExtra("soundfile", models.get(position).getSoundfile());
intent.putExtra("iImage", imageId ); // i pass the int id then you can use this id in your next activity.
mContext.startActivity(intent);
return;
}
});
}
新建Activity
ImageView imageView;
Intent intent = getIntent();
if (intent != null && !intent.getExtras().isEmpty()){
int imageResourceId = intent.getIntExtra("iImage",-1);
imageView.setImageResource(imageResourceId);
}
如何将 RecyclerView
中的图像数组传递给 NewActivity.java
?我不是说来自 row.xml
的图像 - 我想要一组不同于 row.xml
到 NewActivity
的新图像。我将图像保存在可绘制文件夹中。
我下面的试验是相关的类和activity。
文件String.xml
<string-array name="array_titles">
<item>"<![CDATA[[01] general focus]]>"</item>
<item>"<![CDATA[[02] general view for delibration]]>"</item>
</string-array>
<string-array name="array_lyrics">
<item>"<![CDATA[general]]>"</item>
<item>"<![CDATA[ General ]]>"</item>
<item>"<![CDATA[ General ]]>"</item>
<item>"<![CDATA[ General ]]>"</item>
</string-array>
<string-array name="newbrandDesc">
<item>"<![CDATA[ description here ]]>"</item>
<item>"<![CDATA[ description here ]]>"</item>
<item>"<![CDATA[ description here ]]>"</item>
<item>"<![CDATA[ here ]]>"</item>
</string-array>
文件MainActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<View
android:id="@+id/viewerage"
android:background="#01312D"
android:layout_width="match_parent"
android:layout_height="5dp" />
<!-- First Row-->
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="70dp"
android:layout_below="@id/viewerage"
style="@style/scrollbar_shape_style"
android:id="@+id/recyclerview">
</androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>
文件MainActivity.java
public class MainActivity extends AppCompatActivity {
private String TAG = "MainActivity ----- ; ";
private static MediaPlayer player;
String soundfile;
TextView mDetailTv1;
RecyclerView mRecyclerview;
MyAdapter myAdapter;
int [] MusicFile;
List<String> title, newDesc, description;
int[] icon;
ArrayList<Model> arrayList = new ArrayList<Model>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("Intro Songs");
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Listview icons for song titles in position
icon = new int[]{R.drawable.song, R.drawable.song, R.drawable.song, };
mRecyclerview = findViewById(R.id.recyclerview);
mRecyclerview.setLayoutManager(new LinearLayoutManager(this));
title = Arrays.asList(getResources().getStringArray(R.array.array_titles));
// listview descriptions for songs in position
description = Arrays.asList(getResources().getStringArray(R.array.array_lyrics));
// listview NewDescriptions (NewActivity) for songs in position
newDesc = Arrays.asList(getResources().getStringArray(R.array.newbrandDesc));
// listview soundfile file for songs in position
MusicFile = new int[] {R.raw.wex_1, R.raw.wex_2, R.raw.wex_3, , };
for (int i = 0; i< title.size(); i++) {
Model model = new Model(title.get(i), description.get(i), newDesc.get(i), icon[i], MusicFile[i]);
// Bind all strings in an array
arrayList.add(model);
}
// Pass result to listview class
myAdapter = new MyAdapter(this, arrayList);
// Bind the adapter to the listview class
mRecyclerview.setAdapter(myAdapter);
}
@Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainActivity.this.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
myAdapter.getFilter().filter(query);
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
myAdapter.getFilter().filter(newText);
return false;
}
});
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Toast.makeText(this, "Favorites Selected", Toast.LENGTH_SHORT).show();
startActivity(new Intent(this, FavoritesActivity.class));
return true;
// Do more funtionality here
}
return super.onOptionsItemSelected(item);
}
}
文件MyAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyHolder> implements Filterable {
Context mContext;
ArrayList<Model> models, filterList; // This array list create a list of array
// which parameter define in our class
CustomFilter filter;
public MyAdapter(Context context, ArrayList<Model> models) {
this.mContext = context;
this.models = models;
this.filterList = models;
}
@NonNull
@Override
public MyHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row, null); // This line inflate our row
return new MyHolder(view); // This will return our view to holder class
}
@Override
public void onBindViewHolder(@NonNull final MyHolder myHolder, int i) {
myHolder.mTitle.setText(models.get(i).getTitle()); // Here is position
myHolder.mDesc.setText(models.get(i).getDesc());
myHolder.mImageView.setImageResource(models.get(i).getIcon()); // Here we used an image resource
myHolder.setItemCLickListener(new ItemClickListener() {
@Override
public void onItemClickListener(View v, int position) {
String gTitle = models.get(position).getTitle();
String gDesc = models.get(position).getDesc();
BitmapDrawable bitmapDrawable = (BitmapDrawable)myHolder.mImageView.getDrawable();
Bitmap bitmap = bitmapDrawable.getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] bytes = stream.toByteArray();
//get our data with intent
Intent intent = new Intent(mContext, NewActivity.class);
intent.putExtra("actionBarTitle", models.get(position).getTitle());
intent.putExtra("brandNewDesc", models.get(position).getBrandNewDesc());
intent.putExtra("soundfile", models.get(position).getSoundfile());
intent.putExtra("iImage", bytes);
mContext.startActivity(intent);
return;
}
});
}
@Override
public int getItemCount() {
return models.size();
}
@Override
public Filter getFilter() {
if (filter == null) {
filter = new CustomFilter(filterList, this);
}
return filter;
}
}
文件MyHolder.java
public class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView mImageView;
TextView mTitle, mDesc;
ItemClickListener itemCLickListener;
MyHolder(@NonNull View itemView) {
super(itemView);
this.mImageView = itemView.findViewById(R.id.mainIcon);
this.mTitle = itemView.findViewById(R.id.mainTitle);
this.mDesc = itemView.findViewById(R.id.mainDesc);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
this.itemCLickListener.onItemClickListener(v, getLayoutPosition());
}
public void setItemCLickListener(ItemClickListener ic) {
this.itemCLickListener = ic;
}
}
文件CustomFilter.java
private ArrayList<Model> filterList;
private MyAdapter adapter;
public CustomFilter(ArrayList<Model> filterList, MyAdapter adapter) {
this.filterList = filterList;
this.adapter = adapter;
}
@Override
protected FilterResults performFiltering(CharSequence constraints) {
FilterResults filterResults = new FilterResults();
if (constraints != null && constraints.length() > 0) {
constraints = constraints.toString().toUpperCase();
ArrayList<Model> filterModels = new ArrayList<>();
for (int i = 0; i < filterList.size(); i++) {
if (filterList.get(i).getTitle().toUpperCase().contains(constraints)) {
filterModels.add(filterList.get(i));
}
}
filterResults.count = filterModels.size();
filterResults.values = filterModels;
}
else {
filterResults.count = filterList.size();
filterResults.values = filterList;
}
return filterResults;
}
@Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
adapter.models = (ArrayList<Model>) filterResults.values;
adapter.notifyDataSetChanged();
}
}
文件ItemClickListener.java-界面
public interface ItemClickListener {
void onItemClickListener(View v, int position);
}
public class NewActivity extends AppCompatActivity {
private String TAG = "NewActivity ----- ; ";
// Store instance variables
private String title;
private int page;
TextView mBrandNewDesc;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Keeps Android screen on while reading through
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
ActionBar actionBar = getSupportActionBar();
mBrandNewDesc = findViewById(R.id.textView);
// Get data from previous activity when item of activity is clicked using intent
Intent intent = getIntent();
String mActionBarTitle = intent.getStringExtra("actionBarTitle");
String newDescription = intent.getStringExtra("brandNewDesc");
// setctionBar Title
actionBar.setTitle(mActionBarTitle);
// Get text in text textView
mBrandNewDesc.setText(Html.fromHtml(newDescription));
// OK, we are done. Let’s run the project
}
@Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
}
而不是 drawable>bitmap>byteArray
发送可绘制资源 ID,如下面的代码更改了 onBindViewHolder
@Override
public void onBindViewHolder(@NonNull final MyHolder myHolder, int i) {
myHolder.mTitle.setText(models.get(i).getTitle()); //here is position
myHolder.mDesc.setText(models.get(i).getDesc());
myHolder.mImageView.setImageResource(models.get(i).getIcon()); // here we used imge resource
myHolder.setItemCLickListener(new ItemClickListener() {
@Override
public void onItemClickListener(View v, int position) {
String gTitle = models.get(position).getTitle();
String gDesc = models.get(position).getDesc();
int imageId = models.get(position).getIcon();
//get our data with the intent
Intent intent = new Intent(mContext, NewActivity.class);
intent.putExtra("actionBarTitle", models.get(position).getTitle());
intent.putExtra("brandNewDesc", models.get(position).getBrandNewDesc());
intent.putExtra("soundfile", models.get(position).getSoundfile());
intent.putExtra("iImage", imageId ); // i pass the int id then you can use this id in your next activity.
mContext.startActivity(intent);
return;
}
});
}
新建Activity
ImageView imageView;
Intent intent = getIntent();
if (intent != null && !intent.getExtras().isEmpty()){
int imageResourceId = intent.getIntExtra("iImage",-1);
imageView.setImageResource(imageResourceId);
}