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

我有一个Activity,其中包含许多 fragment 。这些 fragment 之一称为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);
    }
}
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
   }
}

因此,一切正常。问题是,我需要BookGridFragment知道用户何时触摸BookGrid并将该信息传递给另一个Fragment(通过Activity)。因此,我假设到达onTouchEvent时,应该以某种方式通知BookGridFragment触摸了BookGrid,但是我不知道该怎么做。

我在网上找到的所有内容都是关于在Fragments之间传递信息,但是这种方法在这里不起作用,因为BookGrid类并不“知道”它在BookGridFragment中。

最佳答案

您可以使用与传达 fragment 和 Activity 相同的想法。创建一个接口(interface):

public interface OnBookGridTouched{
    void onTouchGrid();
}

向您的BookGrid中添加一个变量:
private OnBookGridTouched mCallback;

将 setter 添加到此变量:
public void setCallback(OnBookGridTouched callback){
    mCallback = callback;
}

然后使您的 fragment 实现接口(interface):
public class BookGridFragment extends Fragment implements OnBookGridTouched  {

您将被强制实现onTouchGrid方法

在 fragment onCreateView中,将 fragment 传递到自定义 View :
myBookGrid.setCallback(this);

最后,在您的自定义 View 中,您可以调用回调来引用该 fragment :
 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();
   }

10-08 14:43