这是一个简单的复用Fragment的小案例,比较基础,需要熟练,我们常常使用Fragment来显示一些UI控件,但是Fragment 不必像Activity一样一定要拥有一个UI控件。如果不复写onCreateView(),Fragment可以作为一个纯粹的数据源或者其他模块而存在。这种机制可以很好地将应用程序中的模型部分进行模块化处理,因为FragmentManager会使得Fragment之间的访问变得简单。
案例描述:用三个fragmeng演示一个简单的概要-详情类的应用程序,宿主Fragment显示一个用户可以访问的网站列表,详情Fragment则通过一个WebView来显示选中网站列表条目后的详细URL信息。第三个Fragment是没有UI界面的,它用来为其他Fragment提供模型数据。
DataFragment.java
**
* 封装应用程序的数据逻辑
*/
public class DataFragment extends Fragment {
public static String TAG= DataFragment.class.getSimpleName();
public static class DataItem{
private String mName;
private String mUrl;
public DataItem(String mName, String mUrl) {
this.mName = mName;
this.mUrl = mUrl;
}
public String getmName() {
return mName;
}
public String getmUrl() {
return mUrl;
}
}
//用来创建新的实例
public static DataFragment newInstance(){
return new DataFragment();
}
private ArrayList<DataItem> mDataSet;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//构建初始化数据
mDataSet = new ArrayList<DataItem>();
mDataSet.add(new DataItem("Baidu", "https://www.baidu.com"));
mDataSet.add(new DataItem("CSDN", "http://www.csdn.net"));
mDataSet.add(new DataItem("Android", "http://www.android.com"));
}
public ArrayList<DataItem> getLatestData(){
return mDataSet;
}
}
宿主MasterFragment.java
/**
* 宿主视图Fragment
*/
public class MasterFragment extends DialogFragment implements AdapterView.OnItemClickListener {
public static String TAG= MasterFragment.class.getSimpleName();
/*
* 回调接口,用来将选择的数据反馈给父Activity
* */
public interface OnItemSelectedListener{
void onDataItemSelected(DataFragment.DataItem selected);
}
//用来创建实例
public static MasterFragment newInstance(){
return new MasterFragment();
}
private ArrayAdapter<DataFragment.DataItem> mAdapter;
private OnItemSelectedListener mItemSelectedListener;
/*
* 连接监听器接口,并且确保我们要关联的Activity支持该接口
* */
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mItemSelectedListener= (OnItemSelectedListener) activity;
}catch (ClassCastException e){
throw new IllegalArgumentException("Activity must implement OnItemSelectedListener");
}
}
/*
* 构建一个自定义适配器来显示数据模型中的name字段
* */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAdapter=new ArrayAdapter<DataFragment.DataItem>(getActivity(),
android.R.layout.simple_list_item_1){
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row=convertView;
if(row==null){
row=LayoutInflater.from(getContext()).inflate(android.R.layout.simple_list_item_1,
parent,false);
}
DataFragment.DataItem item = getItem(position);
TextView tv = (TextView) row.findViewById(android.R.id.text1);
tv.setText(item.getmName());
return row;
}
};
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ListView list = new ListView(getActivity());
list.setOnItemClickListener(this);
list.setAdapter(mAdapter);
return list;
}
/*
* 可以直接访问要显示的对话框,设置对话框的标题
* */
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
dialog.setTitle("Select a title");
return dialog;
}
/*
* 从DataFrament中得到最新的数据信息
* */
@Override
public void onResume() {
super.onResume();
//获得最新数据列表
DataFragment fragment= (DataFragment) getFragmentManager()
.findFragmentByTag(DataFragment.TAG);
if(fragment!=null){
mAdapter.clear();
for(DataFragment.DataItem item:fragment.getLatestData()){
mAdapter.add(item);
}
mAdapter.notifyDataSetChanged();
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//通知Activity
mItemSelectedListener.onDataItemSelected(mAdapter.getItem(position));
//如果对话框显示的,则隐藏它
//在fragment嵌入到某个视图的情况下,这个方法返回false;
boolean showsDialog = getShowsDialog();
if(showsDialog){
dismiss();
}
}
}
/**
* 详情视图.
*/
public class DetailFragment extends Fragment {
private WebView mWebView;
/*
*自定义web客户端启用进度显示。
* */
private WebViewClient mWebViewClient=new WebViewClient(){
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
getActivity().setProgressBarVisibility(true);
}
@Override
public void onPageFinished(WebView view, String url) {
getActivity().setProgressBarIndeterminateVisibility(false);
}
};
//设置一个显示的WebView
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setRetainInstance(true);
mWebView=new WebView(getActivity());
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(mWebViewClient);
return mWebView;
}
//外部方法,用来将一个新的网站内容加载到视图
public void loadUrl(String url){
mWebView.loadUrl(url);
}
}
MainActivity.java
public class MainActivity extends FragmentActivity implements MasterFragment.OnItemSelectedListener {
public static String TAG= MainActivity.class.getSimpleName();
private MasterFragment mMaster;
private DetailFragment mDetail;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//窗口上启用一个进度条
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_main);
setProgressBarIndeterminateVisibility(false);
//加载数据Fragment
DataFragment fragment = (DataFragment) getSupportFragmentManager()
.findFragmentByTag(DataFragment.TAG);
if(fragment==null){
fragment=DataFragment.newInstance();
//保存这个实例
fragment.setRetainInstance(true);
//通过一个tag而不是一个容器id关联fragment
FragmentTransaction ft=
getSupportFragmentManager().beginTransaction();
ft.add(fragment,DataFragment.TAG);
ft.commit();
}
mDetail= (DetailFragment) getSupportFragmentManager()
.findFragmentById(R.id.fragment_detail);
mDetail.setRetainInstance(true);
//或者嵌入到宿主fragment,直接作为dialog显示。
mMaster=MasterFragment.newInstance();
//如果存在容器视图,嵌入fragment
View container=findViewById(R.id.fragment_master);
if(container !=null){
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.fragment_master,mMaster);
ft.commit();
}
}
@Override
public void onDataItemSelected(DataFragment.DataItem selected) {
String s = selected.getmUrl();
//显示详情信息
mDetail.loadUrl(selected.getmUrl());
}
//Button点击事件
public void onShowClick(View v){
mMaster.show(getSupportFragmentManager(),null);
}
}