一、ListFragment有默認的布局文件;
二焕数、自定義適配器
private class CrimeAdapter extends ArrayAdapter{
public CrimeAdapter(List crimes){
this(CrimeListFragment.this.getActivity(),0,crimes);
}
public CrimeAdapter(Context context,int resource, List objects) {
super(context, resource, objects);
}
@NonNull
@Override
publicView getView(intposition, View convertView, ViewGroup parent) {
if(convertView==null){
convertView=CrimeListFragment.this.getActivity().getLayoutInflater().inflate(R.layout.list_item_crime,null);
}
Crimecrime=this.getItem(position);
TextView titleView=(TextView) convertView.findViewById(R.id.crime_list_item_title);
titleView.setText(crime.getmTitle());
TextView dateView=(TextView)convertView.findViewById(R.id.crime_list_item_date);
dateView.setText(crime.getmDate().toString());
CheckBox checkBox=(CheckBox)convertView.findViewById(R.id.crime_list_item_checkbox);
checkBox.setChecked(crime.ismSolved());
returnconvertView;
}
}
三纱昧、在Fragment中關(guān)聯(lián)適配器,并給適配器傳入業(yè)務數(shù)據(jù)
public void onCreate(@NullableBundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentActivity activity=this.getActivity();//托管的activity
activity.setTitle(R.string.crime_title);
this.mCrimes=CrimeLab.get(activity).getCrimes();
// ArrayAdapter adapter=new ArrayAdapter(activity,android.R.layout.simple_expandable_list_item_1,mCrimes);
CrimeAdapter adapter=newCrimeAdapter(this.mCrimes);//this.mCrimes就是業(yè)務數(shù)據(jù)
this.setListAdapter(adapter);
}
四堡赔、抽象Activity調(diào)用Fragment的代碼识脆,方便復用
public abstract class SingleFragmentActivity extends AppCompatActivity {
protected abstractFragment createFragment();
@Override
protected voidonCreate(@NullableBundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_fragment);
FragmentManager fManager=this.getSupportFragmentManager();
Fragmentfragment=fManager.findFragmentById(R.id.fragmentContainer);
if(fragment==null){
fragment=this.createFragment();
fManager.beginTransaction().add(R.id.fragmentContainer,fragment).commit();
}
}
}
五、在Activity中調(diào)用Fragment
public class CrimeListActivity extends SingleFragmentActivity {
@Override
protectedFragment createFragment() {
return new CrimeListFragment();
}
}