我正在尝试在RecyclerAdapter Object.keys(features)
中包含的ImageView中加载缩略图,但这需要一个上下文。从RecyclerAdapter可以获得我的应用程序的MainActivity的上下文?我想要这样做,还是应该将图像加载到别处?
这些是我的课程。当然,RecyclerAdapater不会编译,但它代表了我正在尝试做的事情。
MainActivity:
Picasso.with(context).load(stringUrl).into(imageView);
RecyclerAdapter:
public class MainActivity extends AppCompatActivity implements MainScreenContract.View {
ArrayList<String> list;
// Objects for RecyclerView
private RecyclerView recyclerView;
private RecyclerView.Adapter recyclerAdapter;
private RecyclerView.LayoutManager recyclerLayoutManager;
@Inject
MainScreenPresenter mainPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Timber.plant(new Timber.DebugTree() {
// Add the line number to the tag
@Override
protected String createStackElementTag(StackTraceElement element) {
return super.createStackElementTag(element) + ':' + element.getLineNumber();
}
});
// RecyclerView implementation
recyclerView = (RecyclerView) findViewById(R.id.my_list);
// set to true because all images will be the same size
recyclerView.setHasFixedSize(true);
recyclerLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerLayoutManager);
DaggerMainScreenComponent.builder()
.netComponent(((App) getApplicationContext()).getNetComponent())
.mainScreenModule(new MainScreenModule(this))
.build().inject(this);
//Call the method in MainPresenter to make Network Request
mainPresenter.loadVideo();
}
@Override
public void showVideos(Video video){
// Loop through the posts, get the title of the post, and add it to our list object
// TODO: Simplify these references with a variable?
for(int i = 0; i < video.getResults().size(); i++){
// TODO: add second for loop, or simplyfy and get rid of Video object
list.add(video.getResults().get(i).getSiteDetailUrl());
//list.add(video.get(i).getSiteDetailUrl());
Timber.d("List item " + i + " = " + list.get(i));
}
// RecyclerView implementation
recyclerAdapter = new MainScreenRecyclerAdapter(list);
recyclerView.setAdapter(recyclerAdapter);
}
@Override
public void showError(String message){
// Show error message text as a Toast message
Toast.makeText(getApplicationContext(), "Error" + message, Toast.LENGTH_SHORT).show();
Timber.e("Error: " + message);
}
@Override
public void showComplete(){
// Show completed Toast message
Toast.makeText(getApplicationContext(), "Complete", Toast.LENGTH_SHORT).show();
}
}
谢谢!
答案 0 :(得分:1)
您需要将上下文作为构造函数参数传递,然后使用此上下文
private Context mContext;
public MainScreenRecyclerAdapter (Context context) {
mContext = context;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
String imageUrl = dataset.get(position);
Timber.d("Image URL: " + imageUrl);
ImageView view = holder.imageView;
Picasso.with(MainActivity.context).load(imageUrl).into(view);
}