我有一个活动类,其中图像显示在2列的网格视图中。我使用以下代码显示图像
public class BooksPage extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
String image[] = { "http://ecx.images-amazon.com/images/I/51cGqWqQPJL._SX258_BO1,204,203,200_.jpg"
,"http://ecx.images-amazon.com/images/I/91WAYiiPwML.jpg"
,"http://ecx.images-amazon.com/images/I/51CEndEnxCL._SX383_BO1,204,203,200_.jpg"
,"https://s3-ap-southeast-1.amazonaws.com/prod-textnook/bookimages/9788185749815.jpg"
,"http://ecx.images-amazon.com/images/I/51DyYdNU5mL.jpg"
,"http://ecx.images-amazon.com/images/I/61yhyD3HvkL.jpg"
,"http://www.skkatariaandsons.com/Best%20Sellers/978-81-85749-73-0.jpg"
,"http://ecx.images-amazon.com/images/I/81FGjPtdvnL.jpg"};
String stream[]= {"MSC Physics","MSC Chemistry","MSC Biology",
"MSC Geology","BBS|BBA","CA","Bachelor","+2 Science"};
TextView navName,navEmail;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_books_page);
RecyclerView favPlaces = (RecyclerView) findViewById(R.id.favPlaces);
StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
favPlaces.setLayoutManager(layoutManager);
favPlaces.setHasFixedSize(true);
ArrayList<BookDetails> placeList = getPlaces();
StaggeredAdapter staggeredAdapter = new StaggeredAdapter(this,placeList);
favPlaces.setAdapter(staggeredAdapter);
navName.setText(PreferenceManager.getDefaultSharedPreferences(this).getString("name","null"));
navEmail.setText(PreferenceManager.getDefaultSharedPreferences(this).getString("email","null"));
}
private ArrayList<BookDetails> getPlaces() {
ArrayList<BookDetails> details = new ArrayList<>();
for (int index=0; index<image.length;index++){
details.add(new BookDetails(image[index],stream[index]));
}
return details;
}
}
}
但是我不想使用url,而是使用可绘制文件夹中的图像。
我该怎么办。请帮助。
谢谢。
答案 0 :(得分:3)
您需要使用可绘制文件夹中的图像创建一个整数数组。
代码:
//Array of images from drawable folder
int images[] = {R.drawable.image1,R.drawable.image2,R.drawable.image3,...};
//Your method still working without problem.
private ArrayList<BookDetails> getPlaces() {
ArrayList<BookDetails> details = new ArrayList<>();
for (int index = 0; index < images.length; index++){
details.add(new BookDetails(image[index],stream[index]));
}
return details;
}
您可能需要调整您的 BookDetails 类,因为现在您使用的是整数而不是字符串,并且应该更改 StaggeredAdapter 以从资源而不是从URL加载图像。
希望对您有帮助。