Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
688 views
in Technique[技术] by (71.8m points)

android - Button in Fragment's ListView item Interface Definition?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...