Eclipse 生成的主细节流在扩展的类中有一些回调魔法ListFragment
——我说魔法是因为当你是 Android 和 Java 菜鸟时,这就是它的样子:)
鉴于下面的代码,有人可以为我回答几个问题:
- 的
onAttach
方法是ListFragment
做什么用的mCallbacks = (Callbacks) activity
? - 哪个方法在方法中
onItemSelected
被调用,需要实现的方法还是在方法中?onListItemClick
ListFragment
onItemSelected
FragmentActivity
- 所有这些
onItemSelected
方法都采用 anid
of 类型String
(因为DummyContent
id
is aString
)。如果我更改DummyContent
id
为 a ,我需要更改long
哪些方法?onItemSelected
我试着换了一个,FragmentActivity
但这有@Override
,所以我不被允许:(
谢谢
public class RecordingListFragment extends ListFragment {
private static final String STATE_ACTIVATED_POSITION = "activated_position";
private Callbacks mCallbacks = sDummyCallbacks;
private int mActivatedPosition = ListView.INVALID_POSITION;
public interface Callbacks {
public void onItemSelected(String id);
}
private static Callbacks sDummyCallbacks = new Callbacks() {
@Override
// NEEDS IMPLEMENTATION - i guess????
public void onItemSelected(String id) {
}
};
...
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (!(activity instanceof Callbacks)) {
throw new IllegalStateException("Activity must implement fragment's callbacks.");
}
mCallbacks = (Callbacks) activity;
}
@Override
public void onDetach() {
super.onDetach();
mCallbacks = sDummyCallbacks;
}
@Override
public void onListItemClick(ListView listView, View view, int position, long id) {
super.onListItemClick(listView, view, position, id);
mCallbacks.onItemSelected(DummyContent.ITEMS.get(position).id);
}
...
}
还有一个文件...
public class RecordingListActivity extends FragmentActivity
implements RecordingListFragment.Callbacks {
private boolean mTwoPane;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recording_list);
getActionBar().setDisplayHomeAsUpEnabled(true);
if (findViewById(R.id.recording_detail_container) != null) {
mTwoPane = true;
((RecordingListFragment) getSupportFragmentManager()
.findFragmentById(R.id.recording_list))
.setActivateOnItemClick(true);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onItemSelected(String id) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(RecordingDetailFragment.ARG_ITEM_ID, id);
RecordingDetailFragment fragment = new RecordingDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.recording_detail_container, fragment)
.commit();
} else {
Intent detailIntent = new Intent(this, RecordingDetailActivity.class);
detailIntent.putExtra(RecordingDetailFragment.ARG_ITEM_ID, id);
startActivity(detailIntent);
}
}
}