我正在使用 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
被触摸了,但我想不通了解如何做到这一点。
我在网上找到的所有内容都是关于在 fragment 之间传递信息,但这种方法在这里不起作用,因为 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();
}
关于java - 我如何在类和使用它的 fragment 之间进行通信?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50955935/