android接口对象为null

时间:2016-08-17 08:00:28

标签: android android-fragments

我有一个带有 -

的子片段
private FavouriteMessageListener favouriteMessageListener;

msgListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                FavouriteMessageWrapper favouriteMessage =  favourites.get(position);
                String favoriteMessage = favouriteMessage.getText();
                //Need to notify the interface about it
                favouriteMessageListener.favouriteMessageString(favoriteMessage);
                }
            });

我的界面

public interface FavouriteMessageListener {
     void favouriteMessageString(String favouriteMessage);
}

My MainFragment

@Override
    public void favouriteMessageString(String favouriteMessage) {

    }

为什么我的favouriteMessageListener为空?我的实现有什么问题......我只需要使用这个接口在MainFragment中获取string的值。我该怎么办?

1 个答案:

答案 0 :(得分:0)

试试这个

在适配器中

 // Define listener member variable
private static OnItemClickListener listener;
// Define the listener interface
public interface OnItemClickListener {
    void onItemClick(View itemView, int position, String favoriteMessaage);
}
// Define the method that allows the parent activity or fragment to define the listener
public void setOnItemClickListener(OnItemClickListener listener) {
    this.listener = listener;
}

在适配器ViewHolder中:

plus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (listener != null)
                    listener.onItemClick(v, k, favoriteMessage);
            }
        });

在你的片段中:

adapter.setOnItemClickListener(new MenuListCustomAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position, String favoriteMessage) {


              // you can get your String here
              //you can check which view was clicked
               if(view.getId() == R.id.viewID){

                 //do your stuff here
               }
      }
    });