2

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.

4

1 回答 1

4

如果你想要它在列表项上单击

片段 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);

    }   
}

容器活动:

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); 
        }

    }


 }

第二个片段:

public class SecondFragment extends Fragment {

    ...
    public void UpdateUI(Position)
    {

    }

}

希望这可以帮助。单击每个列表项中的按钮可能有点困难,但请尝试相同的方法。可能您必须编写接口声明并调用自定义适配器。

于 2013-03-08T14:32:40.140 回答