我认为在onCreateView中设置监听器并没有错。您的代码可能还有其他问题。(需要更多细节来说明您的代码有什么问题。)
以下是 Android SDK 附带的示例代码。(内容片段.java)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mContentView = inflater.inflate(R.layout.content_welcome, null);
final ImageView imageView = (ImageView) mContentView.findViewById(R.id.image);
mContentView.setDrawingCacheEnabled(false);
// Handle drag events when a list item is dragged into the view
mContentView.setOnDragListener(new View.OnDragListener() {
public boolean onDrag(View view, DragEvent event) {
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_ENTERED:
view.setBackgroundColor(
getResources().getColor(R.color.drag_active_color));
break;
case DragEvent.ACTION_DRAG_EXITED:
view.setBackgroundColor(Color.TRANSPARENT);
break;
case DragEvent.ACTION_DRAG_STARTED:
return processDragStarted(event);
case DragEvent.ACTION_DROP:
view.setBackgroundColor(Color.TRANSPARENT);
return processDrop(event, imageView);
}
return false;
}
});
// Show/hide the system status bar when single-clicking a photo.
mContentView.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
if (mCurrentActionMode != null) {
// If we're in an action mode, don't toggle the action bar
return;
}
if (mSystemUiVisible) {
setSystemUiVisible(false);
} else {
setSystemUiVisible(true);
}
}
});
// When long-pressing a photo, activate the action mode for selection, showing the
// contextual action bar (CAB).
mContentView.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View view) {
if (mCurrentActionMode != null) {
return false;
}
mCurrentActionMode = getActivity().startActionMode(
mContentSelectionActionModeCallback);
view.setSelected(true);
return true;
}
});
return mContentView;
}