从Main Activity到Fragment Adapter的调用方法

时间:2017-12-09 09:41:27

标签: java android android-adapter

如何从我的活动中调用方法到我的片段适配器?我在我的片段上使用 RecyclerView ,并且在此片段适配器中有意图。我已经在我的主要活动中创建了一个方法,但是我无法从我的片段适配器中调用它。

主要活动中的方法

public void showInterstitial() {
  if(interstitialAd != null && interstitialAd.isLoaded()) {
     interstitialAd.show();
     loadingIklan=true;
  }
}

我希望将该方法放在片段适配器

上的意图切换案例中
    public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.ViewHolder> {


    public static class ViewHolder extends RecyclerView.ViewHolder {

        private TextView homeTitle;

        private Context context;

        public ViewHolder(View itemView) {
            super(itemView);
            context = itemView.getContext();
            homeTitle = (TextView)itemView.findViewById(R.id.homeTitle);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    final Intent intent;
                    switch (getAdapterPosition()) {
                        case 0:
                            ((MainActivity) getActivity()).showInterstitial();
                            intent = new Intent(context, AllBlock.class);
                            break;
                        case 1:
                            intent = new Intent(context, BasicBlock.class);
                            break;

                        default:
                            intent = new Intent(context, AllBlock.class);
                            break;
                    }
                    context.startActivity(intent);
                }
            });
        }
    }


    public List<HomeData> homeList;

    public HomeAdapter(List<HomeData> homeList) {

        this.homeList = homeList;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.home_item, parent, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.homeTitle.setText(homeList.get(position).getHomeTitle());
    }

    @Override
    public int getItemCount() {
        return homeList.size();
    }
}

我的主要片段

public class Home extends Fragment {


    public Home() {
        // Required empty public constructor
    }


    private RecyclerView recyclerView;
    private HomeAdapter homeAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.home, container, false);

        recyclerView = (RecyclerView)view.findViewById(R.id.recyclerview);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);

        homeAdapter = new HomeAdapter(homeDataList());
        recyclerView.setAdapter(homeAdapter);

        return view;
    }
}

任何人都可以用正确的代码帮助我吗?谢谢。

2 个答案:

答案 0 :(得分:1)

您不应该从RecyclerView适配器调用活动。适配器应该只处理数据显示。因此,您需要一个Listener / Callback模式。因为您的适配器是从片段调用的,其中片段附加到活动,所以您需要创建一个嵌套的Listener / Callback。

首先,在RecyclerView适配器中创建侦听器接口。接口的目的是告诉监听器(Fragment)做某事。

public class YourAdapter extends RecyclerView.Adapter<YourAdapter.ViewHolder> {

  ...
  private AdapterListener listener;

  // define the listener
  public interface AdapterListener {
    void onItemClicked(int position);
  }

  // register the listener with this method
  public setListener(AdapterListener listener) {
    this.listener = listener;
  }

  ...

  public ViewHolder(View itemView) {
    itemView.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View view) {

         // tell the listener about the click
         if(listener != null) {
           listener.onItemClicked(getAdapterPosition());
         }

       }
  }

}

第二次,将片段注册为侦听器:

public class YourFragment extends Fragment {
  ...
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    ...
    // This is an example, you can register the listener in any method

    // sample
    YourAdapter adapter = new YourAdapter(...);

    YourAdapter.AdapterListener listener = new YourAdapter.AdapterListener {
       @Override
       public void onItemClicked(int position) {

         // handle the item click here.
       }
    }
  }
}

第三次,创建侦听器以在片段和活动之间进行通信(在Communicating with Other Fragments阅读更多内容:

public class YourFragment extends Fragment {
  private FragmentListener mListener;

  public interface FragmentListener {
    onRecyclerViewItemClicked(int position);
  }

  @Override
  public void onAttach(Context context) {
    super.onAttach(context);

    // This makes sure that the container activity has implemented
    // the callback interface. If not, it throws an exception
    try {
        mCallback = (FragmentListener) context;
    } catch (ClassCastException e) {
        throw new ClassCastException(context.toString()
                + " must implement FragmentListener");
    }
  }

}

第四,执行片段监听器,告诉活动有关recyclelerView项目的点击。在以前的Adapter侦听器中添加代码:

public class YourFragment extends Fragment {
  ...
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    ...
    // This is an example, you can register the listener in any method

    YourAdapter adapter = new YourAdapter(...);

    YourAdapter.AdapterListener listener = new YourAdapter.AdapterListener {
       @Override
       public void onItemClicked(int position) {
         mListener.onRecyclerViewItemClicked(position);
       }
    }
  }
}

第五,将活动注册为侦听接收者。因此,你做了实际的逻辑:

public class YourActivity extends Activity
        implements YourFragment.FragmentListener {

  ...

  @Ovveride
  public void onRecyclerViewItemClicked(int position) {
    // Handle the RecyclerView item click here
    switch(position) {
      case 0:
        showInterstitial();
        break;
     default:
       intent = new Intent(this, AllBlock.class);
       startActivity(intent);
    }
  }
}

注意:

我倾向于将事件总线机制与EventBus一起使用,因为它简化了所有侦听器代码。在掌握了监听器/回调模式后,您可以尝试使用EventBus。的 Horas!

答案 1 :(得分:0)

interfacesample.java

public interface sample{
      function onclick();
}

activity.java

class activity extends appcombatactivity implements sample{
         override onclick(){
//do whatever you want to do
}

}

// adapter.java

switch (getAdapterPosition()) {
                            case 0:
                            //getActivity show red code//
                               (context as activity).onclick()

                                break;
                            default:
                                intent = new Intent(context, AllBlock.class);
                                break;
                        }
这样的事情。希望你能理解。如果有任何疑问,请告诉我。