@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_item_new_crime: Crime crime = new Crime(); CrimeLab.get(getActivity()).addCrime(crime); Intent i = new Intent(getActivity(), CrimePagerActivity.class); i.putExtra(CrimeFragment.EXTRA_CRIME_ID, crime.getmId()); startActivityForResult(i, REQUEST_NEW_CRIME); return true; default: return super.onOptionsItemSelected(item); } }
@Override public void onListItemClick(ListView l, View v, int position, long id) { // getKistAdapter()是ListFragment类的便利方法,该方法可返回设置在ListFragment列表视图上的adapter。 // 调用adapter的getItem(int)方法,把结果转换成Crime对象 Crime c = (Crime) (getListAdapter()).getItem(position); // 必须类型转换 // Log.d(TAG, c.getmTitle()+ " was clicked."); // start CrimeActivity // Intent i = new Intent(getActivity(), CrimeActivity.class); // start CrimePagerActivity Intent i = new Intent(getActivity(), CrimePagerActivity.class); i.putExtra(CrimeFragment.EXTRA_CRIME_ID, c.getmId()); startActivityForResult(i, REQUEST_MODIFIED_CRIME); }
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { // 获取 crime Log.i(TAG, "Return from CrimeFragment."); Crime crime = (Crime) data.getSerializableExtra(CrimeFragment.SER_KEY); int pos = -1; // 找到 返回的 Crime 是 mCrimes 中的第几条记录来,后续用来决定是否修改 for (int i = 0; i < mCrimes.size(); i++) { if (mCrimes.get(i).getmId().equals(crime.getmId())) { pos = i; break; } } // 根据请求码决定是“新增”、“修订”哪个发出的请求 switch (requestCode) { case REQUEST_NEW_CRIME: // 新增 记录 if (resultCode == Activity.RESULT_OK) // 结果代码是 OK mCrimes.get(pos).setTo(crime); else { // 结果代码是Cancel Log.i(TAG, "_NEW_CRIME_Cancel"); mCrimes.remove(pos); // remove } break; case REQUEST_MODIFIED_CRIME: // 修改记录 if (resultCode == Activity.RESULT_OK) { // 结果代码是OK Log.i(TAG, "_CRIME_MODIFIED_OK_"); mCrimes.get(pos).setTo(crime); } else if (resultCode == Activity.RESULT_CANCELED) { // 结果代码是Cancel Log.i(TAG, "_CRIME_MODIFIED_CANCELED_"); } else if (resultCode == CrimeFragment.DELETE_ITEM) { mCrimes.remove(pos); // remove } break; default: break; } }