Button in Fragment's ListView item Interface D

2019-01-27 01:32发布

In my app, I have an activity that has two fragments in actionbar tabs navigation mode, just like the android developer site example.

in my first fragment I have a listview (which has it's own adapter ) and each item of the listview has a button called +1. I want to refresh the second fragment that shows the items in listview in first fragment that their +1 button's clicked.

I know i have to use interfaces. but I cant figure how to use them. where do I have to define the interface? how to use it? and how to access it from the activity to refresh the second fragment?

a quick help would be great. thanks.

1条回答
男人必须洒脱
2楼-- · 2019-01-27 01:47

If you want it on List Item Click

Fragment A:

public class FragmentA extends ListFragment {

OnItemSelectedListener mListener;

...
// Container Activity must implement this interface
public interface OnItemSelectedListener {
    public void onItemSelected(int position);
}
...

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mListener = (OnItemSelectedListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString() + " must implement OnItemSelectedListener");
    }
}

@Override
public void onListItemClick(ListView l, View v, int position, long id) {

    mCallback.onItemSelected(position);

    }   
}

ContainerActivity:

public class ContainerActivity extends FragmentActivity 
    implements FragmentA.OnItemSelectedListener
{

//...



public void onItemSelected(int Position/*pass anything which u want*/) 
    {

        SecondFragment second_fragment = (SecondFragment) getSupportFragmentManager().findFragmentById(R.id.fragmentB);

        if(second_fragment !=null)
        {
            second_fragment.UpdateUI(Position); 
        }

    }


 }

Second Fragment:

public class SecondFragment extends Fragment {

    ...
    public void UpdateUI(Position)
    {

    }

}

Hope this helps. On click of a Button inside each listitem might be bit difficult, but try the same approach. May be you have to write the interface declaration and call in your custom adapter.

查看更多
登录 后发表回答