import android.annotation.SuppressLint;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.tz.dream_10_16_fragment_phoneandtablet.DetailActivity;
import com.tz.dream_10_16_fragment_phoneandtablet.R;
@SuppressLint("NewApi")
public class MenuFragment extends Fragment implements OnItemClickListener {
private View viewById;
// 今天使用枚举来配置我们的数据(扩展)
public enum MenuType {
Volume("声音", VolumeFragment.class), Display("显示", DisplayFragment.class), Wifi(
"wifi", WifiFragment.class);
// 我们的选项的标题
private String value;
// 我们点击当前这个条目需要启动的对应的fragment
private Class<? extends Fragment> clazz;
private MenuType(String value, Class<? extends Fragment> clazz) {
this.value = value;
this.clazz = clazz;
}
public String getValue() {
return value;
}
public Class<? extends Fragment> getClazz() {
return clazz;
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_menu, null);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ListView menuLV = (ListView) view.findViewById(R.id.lv_menu);
// 赋值
MenuType[] values = MenuType.values();
String[] objects = new String[values.length];
for (int i = 0; i < objects.length; i++) {
objects[i] = values[i].getValue();
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
getActivity(), android.R.layout.simple_list_item_1, objects);
menuLV.setAdapter(arrayAdapter);
menuLV.setOnItemClickListener(this);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
viewById = getActivity().findViewById(R.id.fl_menu);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
MenuType menuType = MenuType.values()[position];
// 首先创建我们的fragment
FragmentTransaction beginTransaction = getFragmentManager()
.beginTransaction();
try {
beginTransaction.replace(R.id.fl_menu, menuType.getClazz()
.newInstance());
beginTransaction.commit();
} catch (java.lang.InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
整理自教程