CustomAdapter上的Android Dagger2依赖注入

时间:2016-12-10 17:38:11

标签: android dependency-injection dagger-2

我在我的android代码中使用Dagger2学习依赖注入,我在使用它时没有任何问题,直到我尝试在ListView的CustomAdapter中注入演示者,它总是返回Null Value。目的是当有人单击ListView项时我想执行Presenter功能。这是我的CustomAdapter看起来像:

public class CustomAdapter extends BaseAdapter {

ArrayList<String> contactNameList, listGroup;
Context context;
ArrayList<Bitmap> contactImages;
ArrayList<Integer> listContactId;

private static LayoutInflater inflater=null;

@Inject
DetailScreenPresenter detailScreenPresenter;

public CustomAdapter(MainActivity mainActivity, ArrayList<String> contactNameList, ArrayList<Bitmap> contactImages, ArrayList<String> listGroup, ArrayList<Integer> listContactId)
{
    this.contactNameList = contactNameList;
    context = mainActivity;
    this.contactImages = contactImages;
    this.listGroup = listGroup;
    this.listContactId = listContactId;
    inflater = ( LayoutInflater )context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {
    return contactNameList.size();
}

@Override
public Object getItem(int position) {
    return position;
}

@Override
public long getItemId(int position) {
    return position;
}

public static class Holder
{

    public Holder(View view,Context context)
    {
        ButterKnife.bind(this,view);

    }

    @BindView(R.id.txtName)
    TextView tvName;

    @BindView(R.id.txtGroup)
    TextView tvGroup;

    @BindView(R.id.imageProfile)
    ImageView img;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

    View rowView;
    rowView = inflater.inflate(R.layout.contact_list, null);
    Holder holder=new Holder(rowView, context);

    holder.tvName.setText(contactNameList.get(position));
    holder.img.setImageBitmap(contactImages.get(position));
    holder.tvGroup.setText(listGroup.get(position));
    rowView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            detailScreenPresenter.loadDetail(listContactId.get(position));
        }
    });
    return rowView;
}
}

这是触发CustomAdapter的MainActivity

public class MainActivity extends AppCompatActivity implements MainScreenContact.View {

@BindView(R.id.listContact)
ListView listView;

ArrayList<String> listName;
ArrayList<Bitmap> listImage;
ArrayList<String> listGroup;
ArrayList<Integer> listContactId;
HashMap<Integer, Bitmap> tempImageArray;
String[] letter={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};


@Inject
MainScreenPresenter mainPresenter;


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

    ButterKnife.bind(this);

    listName = new ArrayList<>();
    listImage = new ArrayList<>();
    tempImageArray = new HashMap<>();
    listGroup = new ArrayList<>();
    listContactId = new ArrayList<>();

    DaggerMainScreenComponent.builder()
            .netComponent(((App) getApplicationContext()).getNetComponent())
            .mainScreenModule(new MainScreenModule(this, new ContactDatabaseHelper(this)))
            .build().inject(this);

    mainPresenter.loadPost();
}


@Override
public void showPosts(List<Post> posts) {

    Collections.sort(posts, new Comparator<Post>() {
        @Override
        public int compare(Post post1, Post post2) {
            String name1=post1.getFirstName()+" "+post1.getLastName();
            String name2=post2.getFirstName()+" "+post2.getLastName();
            return name1.compareToIgnoreCase(name2);
        }
    });

    int indexGroup=0;

    for (int i = 0; i < posts.size(); i++) {

        if(posts.get(i).getProfilePic().contains("http"))
            mainPresenter.loadImage(posts.get(i).getProfilePic(), i);
        else
            mainPresenter.loadImage("http://example.com", i);


        if(Arrays.binarySearch(letter,Character.toString(posts.get(i).getFirstName().charAt(0)).toUpperCase())==-1)
        {
            if(listGroup.size()==0)
                listGroup.add("*");
            else
                listGroup.add(" ");
        }
        else
        {
            if(!listGroup.get(indexGroup).equalsIgnoreCase(Character.toString(posts.get(i).getFirstName().charAt(0)))) {
                listGroup.add(Character.toString(posts.get(i).getFirstName().charAt(0)).toUpperCase());
                indexGroup = i;
            }
            else
                listGroup.add(" ");
        }

        listContactId.add(i, posts.get(i).getId());
        listName.add(i, posts.get(i).getFirstName() + " " + posts.get(i).getLastName());

    }

}


@Override
public void showError(String message) {
    Toast.makeText(getApplicationContext(), "Error" + message, Toast.LENGTH_LONG).show();
}

@Override
public void showComplete() {
    Toast.makeText(getApplicationContext(), "Complete", Toast.LENGTH_LONG).show();
}

@Override
public void setImageProfile(Bitmap profileBmp, int x) {
    tempImageArray.put(x, profileBmp);

    if(tempImageArray.size()==listName.size())
    {

        SortedSet<Integer> keys = new TreeSet<Integer>(tempImageArray.keySet());
        for(Integer key : keys)
        {
            listImage.add(tempImageArray.get(key));
        }

        listView.setAdapter(new CustomAdapter(this, listName, listImage, listGroup, listContactId));
    }

}
}

请帮助注入DetailScreenPresenter演示者的方法。

非常感谢

1 个答案:

答案 0 :(得分:2)

通常,为了对任何对象执行注入,您应该明确地调用<some_dagger_component>.inject(<target_object>)

在你的情况下,你可以这样做:

CustomAdapter adapter = new CustomAdapter(this, listName, listImage, listGroup, listContactId);

DaggerMainScreenComponent.builder()
            .netComponent(((App) getApplicationContext()).getNetComponent())
            .mainScreenModule(new MainScreenModule(this, new ContactDatabaseHelper(this)))
            .build().inject(adapter);

listView.setAdapter(adapter);

但是,你要做的是滥用依赖注入框架 - 你不应该在适配器中执行注入,而只需将所需的对象传递给适配器的构造函数。

this post中,您可以在Android中找到有关依赖注入的其他信息。