一、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中关联适配器,并给适配器传入业务数据
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就是业务数据
this.setListAdapter(adapter);
}
四、抽象Activity调用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中调用Fragment
public class CrimeListActivity extends SingleFragmentActivity {
@Override
protectedFragment createFragment() {
return new CrimeListFragment();
}
}