如何在类和使用它的片段之间进行通信?

Sha*_*ron 6 java android android-fragments

我正在使用Android Studio.我无法在线找到答案,因此即使是解决方案的链接也会有所帮助.

我有一个Activity,其中包括许多碎片.调用BookGridFragment其中一个片段,它使用一个名为的类BookGrid.

BookGridFragment 看起来像这样(我遗漏了不相关的位):

public class BookGridFragment extends Fragment {

    BookGrid myBookGrid;

    public BookGridFragment() {}

    @Override
    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

        // Inflate layout
        View rootView = inflater.inflate(
                R.layout.fragment_book_grid, container, false);

        myBookGrid = rootView.findViewById(book_grid);

        return rootView;
    }

    public void setBook(Book thisBook) {
        myBookGrid.setBook(thisBook);
    }
}
Run Code Online (Sandbox Code Playgroud)

BookGrid堂课是:

public class BookGrid extends View {

    private Book mBook;

    public BookGrid(Context thisContext, AttributeSet attrs) {
        super(thisContext, attrs);
    }

    public void setBook(Book newBook) {
        mBook = newBook;
    }

    protected void onDraw(Canvas canvas) {

        if (mBook == null) return; 

        canvas.save();

        draw_book_details(); 
        // draw_book_details() is a function which just takes 
        //  the book info and displays it in a grid

        canvas.restore();
    }

   public boolean onTouchEvent(MotionEvent event) {

       // This function responds to the user tapping a piece of
       //  book info within the grid

       // THIS IS WHERE I'M HAVING PROBLEMS
   }
}
Run Code Online (Sandbox Code Playgroud)

所以,一切正常.问题是,我需要BookGridFragment知道用户何时触摸BookGrid并将该信息传递给另一个Fragment(通过Activity).所以,我认为,当onTouchEvent达到,应该以某种方式通知BookGridFragmentBookGrid被感动了,但我无法弄清楚如何做到这一点.

我在网上找到的所有内容都是关于在片段之间传递信息,但这种方法在这里不起作用,因为BookGrid班级不"知道"它在一个片段内BookGridFragment.

Lev*_*ira 4

您可以使用用于传递 Fragment 和 Activity 的相同想法。创建一个接口:

public interface OnBookGridTouched{
    void onTouchGrid();
} 
Run Code Online (Sandbox Code Playgroud)

向 BookGrid 添加一个变量:

private OnBookGridTouched mCallback;
Run Code Online (Sandbox Code Playgroud)

向该变量添加一个设置器:

public void setCallback(OnBookGridTouched callback){
    mCallback = callback;
}
Run Code Online (Sandbox Code Playgroud)

然后让你的片段实现接口:

public class BookGridFragment extends Fragment implements OnBookGridTouched  {
Run Code Online (Sandbox Code Playgroud)

你将被迫实现该方法onTouchGrid

在片段 onCreateView 中将片段传递给您的自定义视图:

myBookGrid.setCallback(this);
Run Code Online (Sandbox Code Playgroud)

最后,在您的自定义视图中,您可以调用回调来引用片段:

 public boolean onTouchEvent(MotionEvent event) {

       // This function responds to the user tapping a piece of
       //  book info within the grid

       // THIS IS WHERE I'M HAVING PROBLEMS
       mCallback.onTouchGrid();
   }
Run Code Online (Sandbox Code Playgroud)