Java 从适配器调用 Fragment 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24502394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:38:05  来源:igfitidea点击:

Call a Fragment method from an Adapter

javaandroidandroid-fragments

提问by user3713706

I have a method sendData()in my fragment. This method starts a new Activity. I want to call this method from my ArrayAdapter.

sendData()我的片段中有一个方法。此方法启动一个新的 Activity。我想从我的ArrayAdapter.

Here is my code:-

这是我的代码:-

HomeFragment.java

HomeFragment.java

stagAdaper = new StaggeredAdapter(myContext, android.R.layout.simple_list_item_1, getList);
            mGridView.setAdapter(stagAdaper);
    private void sendData(int position)
    {

        myDialog = new ProgressDialog(myContext).show(getActivity(), "Fetching news..", "Just a moment");

        myDialog.getWindow().setContentView(R.layout.openarticlewaitprogress);
        myDialog.getWindow().setTitle("Loading..");
        myDialog.getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
         new  NewsDetails(myDialog);



            Intent nIntent = new Intent(getActivity(),Details.class);

               String Body=getList.get(position).getBody();

            newsIntent.putExtra("Body", Body);


            startActivity(nIntent);

    }

StaggeredAdapter.java

交错适配器.java

viewHolder.layGridLayout.setOnClickListener(new View.OnClickListener() 
    {

        @Override
        public void onClick(View v) 
        {
            // TODO Auto-generated method stub
            //viewHolder.layGridLayout.setForeground(R.drawable.foreground_selector);

        }
    });
    return convertView;
    }

How can I do it?

我该怎么做?

采纳答案by Shivam Verma

Edit :Here is what I would use now. Older, "easier" solutions are available below.

编辑:这是我现在要使用的。下面提供了较旧的“更简单”的解决方案。

MyFragment extends Fragment implements CustomAdapter.EventListener {

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        CustomAdapter adapter = new CustomAdapter(..., this);

    }

    void onEvent(int data) {
        doSomething(data);
    }

}

CustomAdapter extends BaseAdapter {

    EventListener listener; 

    public interface EventListener {
        void onEvent(int data);   
    }

    public CustomAdapter(..., EventListener listener) {
        this.listener = listener; 
    }

    ...

}

Now from any place in the adapter we can call listener.onEvent(data);to trigger the method in the fragment.

现在,我们可以从适配器中的任何位置调用listener.onEvent(data);以触​​发片段中的方法。

Moreover, instead of providing a listener through the constructor, we can add another method in the adapter such as registerListener(EventListener eventListener)and then maintain a list of listeners if needed.

此外,我们可以在适配器中添加另一个方法,而不是通过构造函数提供侦听器registerListener(EventListener eventListener),然后根据需要维护一个侦听器列表。

Old Answer:

旧答案:

Solution 1 : Make the adapter an inner class of your fragment, so that you can call the method directly.

解决方案 1:使适配器成为片段的内部类,以便您可以直接调用该方法。

Solution 2 : Update your adapter constructor to accept the Fragment as a parameter.

解决方案 2:更新您的适配器构造函数以接受 Fragment 作为参数。

Something like :

就像是 :

customAdapter = new CustomAdapter(myContext, android.R.layout.simple_list_item_1, getList, HomeFragment.this);

and update the constructor of the Adapter :

并更新 Adapter 的构造函数:

public CustomAdapter(Context context, int id, HomeFragment fragment) {
    this.fragment = fragment;
}

then you call methods using the fragment variable.

然后您使用片段变量调用方法。

fragment.doSomething();

回答by qulfille

You can make sendData method as static

您可以将 sendData 方法设为静态

public static void sendData(int position)
{
     ......
}

n call it as

n 称之为

@Override
public void onClick(View v) 
{
     // TODO Auto-generated method stub
     HomeFragment.sendData(position)
     ........    
}

回答by Faisal Shaikh

I know it's late to answer but There are 2 ways more to do it:

我知道现在回答已经晚了,但还有两种方法可以做到:

  1. You can also send broadcastfrom adapterand register it in fragment.

  2. Use interface. Refer thisSO question for details.

  1. 您还可以发送broadcastadapter并注册它fragment

  2. 使用界面。有关详细信息,请参阅SO 问题。