在上一篇文章中,已经基本实现了主布局,接下来,我们将加以完善——在这里,要实现上篇文章中提到过的FestivalCategoryFragment
下面是布局文件的实现:
fragment_festival_category.xml
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/id_gv_festival_category"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="3"
android:horizontalSpacing="3dp"
android:padding="16dp"
android:verticalSpacing="2dp" >
</GridView>
布局呢很简单,就是一个GridView
以及GridView的item的布局:
item_festival.xml
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/id_tv_festival_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
android:gravity="center"
android:padding="8dp" />
</android.support.v7.widget.CardView>
这里为了增加立体感,在外层设置一个CardView
但是要添加相应的Library Dependency -> com.android.support:cardview-v7
public class FestivalCategoryFragment extends Fragment {
public static final String ID_FESTIVAL="FestivalId";
private GridView mGridView;
private ArrayAdapter<Festival> mAdapter;
private LayoutInflater mInflater;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_festival_category, container,
false);//注意:是"包名.R"
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
mInflater = LayoutInflater.from(getActivity());
mGridView = (GridView) view.findViewById(R.id.id_gv_festival_category);
mAdapter = new ArrayAdapter<Festival>(
getActivity(), -1, FestivalLab.getInstance().getFestivals()) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item_festival,
parent, false);
}
TextView tv = (TextView) convertView
.findViewById(R.id.id_tv_festival_name);
tv.setText(getItem(position).getName());
return convertView;
}
};
mGridView.setAdapter(mAdapter);
mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent=new Intent(getActivity(), ChooseMsgActivity.class);
intent.putExtra(ID_FESTIVAL,mAdapter.getItem(position).getId());
startActivity(intent);
}
});
}
}
需要注意的是,这里所继承的父类Fragment是来自android.support.v4.app,不要弄错为android.app
(@Nullable 参数可为null)
可以看到,FestivalCategoryFragment的实现比较的容易,还末尾处实现了GridView的点击事件,点击之后跳转到相应的ChooseMsgActivity,用于选择事先提供的祝福短信。