Adapter并没有什么不一样的,就按照普通的写就可以了,这里贴出来主要是做个参考,可以自由发挥。
public class ARecyclerViewAdapter extends RecyclerView.Adapter<ARecyclerViewAdapter.AViewHolder> {
private List<Object> list;
private Context context;
private LayoutInflater inflater;
public void setList(List<Object> list) {
this.list = list;
notifyDataSetChanged();
}
public ARecyclerViewAdapter(Context context, List<Object> list) {
this.context = context;
this.list = list;
inflater = LayoutInflater.from(context);
}
@NonNull
@Override
public AViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.activity_main, parent, false);
return new AViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull AViewHolder holder, int position) {
//不启用ViewHolder复用
holder.setIsRecyclable(false);
}
@Override
public int getItemCount() {
return list.size();
}
class AViewHolder extends RecyclerView.ViewHolder{
public AViewHolder(@NonNull View itemView) {
super(itemView);
}
}
}
这里开始是创建Mudule
@Module
public class AdapterMudule {
????// 申明用到的参数
public List<Object> list;
public Context context;
public AdapterMudule(Context context, List<Object> list) {
this.context = context;
this.list = list;
}
????// 标记和创建返回
@Provides
public Context provideContext() {
return context;
}
????// 标记和创建返回
@Provides
public List<Object> provideList() {
return list;
}
????// 可以不使用@Named这个标记,这里是为了学习命名使用
@Named("adapter")
@Provides
public ARecyclerViewAdapter provideAdapter(Context context, List<Object> list){
return new ARecyclerViewAdapter(context, list);
}
}
创建Component指向一个具体的Activity
@Component(modules = AdapterMudule.class)
public interface AdapterComponent {
void inject(MainActivity activity);
}
在这里写完之后,一定不要忘记Rebuild哟,不然不能生成代码,就不能在Main里使用了
Activity使用Adapter
public class MainActivity extends AppCompatActivity {
????// 可以不使用@Named这个标记,这里是为了学习命名使用
@Named("adapter")
@Inject
ARecyclerViewAdapter adapter;
????private RecyclerView recyclerView;
private List<Object> list = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// recyclerView = findViewById(R.id.recyclerView);
for (int i = 0; i < 10; i++) {
list.add("item" + i);
}
DaggeradapterComponent.builder().adapterMudule(new AdapterMudule(this, list)).build().inject(this);
Log.e("------------->", adapter.getItemCount() + "");
????????recyclerView.setLayoutManager(new GridLayoutManager(this, 1)); ????????recyclerView.setAdapter(adapter);
}
}
|