第65页
showDetails(curCheckPosition); //显示详细内容
}
}
//重写onSaveInstanceState()方法,保存当前选中的列表项的索引值
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curChoice", curCheckPosition);
}
//重写onListItemClick()方法
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
showDetails(position); //调用showDetails()方法显示详细内容
}
void showDetails(int index) {
curCheckPosition = index; //更新保存当前索引位置的变量的值为当前选中值
if (dualPane) { //当在一屏上同时显示列表和详细内容时
getListView().setItemChecked(index, true); //设置选中列表项为选中状态
DetailFragment details = (DetailFragment) getFragmentManager()
.findFragmentById(R.id.detail); //获取用于显示详细内容的Fragment
if (details == null || details.getShownIndex() != index) {
//创建一个新的DetailFragment实例,用于显示当前选择项对应的详细内容
details = DetailFragment.newInstance(index);
//要在activity中管理fragment, 需要使用FragmentManager
FragmentTransaction ft = getFragmentManager()
.beginTransaction(); //获得一个FragmentTransaction的实例
ft.replace(R.id.detail, details); //替换原来显示的详细内容
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); //设置转换效果
ftmit(); //提交事务
}
} else { //在一屏上只能显示列表或详细内容中的一个内容时
//使用一个新的Activity显示详细内容
Intent intent = new Intent(getActivity(),MainActivity.DetailActivity.class); //创建一个Intent对象
intent.putExtra("index", index); //设置一个要传递的参数
startActivity(intent); //开启一个指定的Activity
}
}
}
(4)创建一个继承自Fragment的DetailFragment,用于显示选中标题对应的详细内容。在该类中,首先创建一个DetailFragment的新实例,其中包括要传递的数据包,然后编写一个名称为getShownIndex()的方法,用于获取要显示的列表项的索引,最后再重写onCreateView()方法,设置要显示的内容。DetailFragment类的具体代码如下:
public class DetailFragment extends Fragment {
//创建一个DetailFragment的新实例,其中包括要传递的数据包
public static DetailFragment newInstance(int index) {
DetailFragment f = new DetailFragment();
//将index作为一个参数传递
Bundle bundle = new Bundle(); //实例化一个Bundle对象
bundle.putInt("index", index); //将索引值添加到Bundle对象中
f.setArguments(bundle); //将bundle对象作为Fragment的参数保存
return f;
}
public int getShownIndex() {
return getArguments().getInt("index", 0); //获取要显示的列表项索引
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
return null;
}
ScrollView scroller = new ScrollView(getActivity()); //创建一个滚动视图
TextView text = new TextView(getActivity()); //创建一个文本框对象
text.setPadding(10, 10, 10, 10); //设置内边距
scroller.addView(text); //将文本框对象添加到滚动视图中
text.setText(Data.DETAIL[getShownIndex()]); //设置文本框中要显示的文本
return scroller;
}
}
(5)打开默认创建的MainActivity,在该类中创建一个内部类,用于在手机界面中通过Activity显示详细内容,具体代码如下:
//创建一个继承Activity的内部类,用于在手机界面中通过Activity显示详细内容
public static class DetailActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//判断是否为横屏,如果为横屏,则结束当前Activity,准备使用Fragment显示详细内容
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {