本文出自:http://www.jb51.cc/article/p-baqlrqim-ep.html
一丶效果演示:
二丶需求分析
1.设计简单玩家包涵以下属性
GamePlay:
关卡
分数
游戏ID
2.实现游戏玩家数据的增删改
三丶功能设计
1.展现玩家基本数据
2.分数降序排列
3.管理员可增删改玩家信息
四丶技术实现
1.sqlitem完成数据的基本功能
2.Activity和Fragment交互
3ListVIEw显示玩家信息
五丶代码展示
1.创建entity文件夹存放实体类GamePlayer.java并创建get set toSring方法
public class GamePlayer { private String player; private int score; private int level; private int ID; public GamePlayer() { } public GamePlayer(String player,int score,int level) { this.player = player; this.score = score; this.level = level; } public GamePlayer(String player,int level,int ID) { this.player = player; this.score = score; this.level = level; this.ID = ID; } public String getPlayer() { return player; } public voID setPlayer(String player) { this.player = player; } public int getscore() { return score; } public voID setscore(int score) { this.score = score; } public int getLevel() { return level; } public voID setLevel(int level) { this.level = level; } public int getID() { return ID; } public voID setID(int ID) { this.ID = ID; } @OverrIDe public String toString() { return "GamePlayer{" + "player='" + player + '\'' + ",score=" + score + ",level=" + level + ",ID=" + ID + '}'; }}2.创建db文件夹存放数据库部分(DatabaseAdapter DatabaseHelper GameMetaData)
GameMetaData 数据库元数据
public final class GameMetaData { private GameMetaData() { } //定义表 和 列字段名 public static abstract class GamePlay implements BaseColumns { public static final String table_name = "player_table"; public static final String PLAYER = "player"; public static final String score = "score"; public static final String LEVEL= "level"; }}DatabaseAdapter 数据库 *** 作
public class DatabaseAdapter { private DatabaseHelper dbHelper; public DatabaseAdapter(Context context) { dbHelper = new DatabaseHelper(context); } //添加 *** 作 public voID add(GamePlayer gamePlayer) { sqliteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(GameMetaData.GamePlay.PLAYER,gamePlayer.getPlayer()); values.put(GameMetaData.GamePlay.score,gamePlayer.getscore()); values.put(GameMetaData.GamePlay.LEVEL,gamePlayer.getLevel()); db.insert(GameMetaData.GamePlay.table_name,null,values); db.close(); } //删除 *** 作 public voID delete(int ID) { sqliteDatabase db = dbHelper.getWritableDatabase(); String whereClause = GameMetaData.GamePlay._ID + "=?"; String[] whereArgs = {String.valueOf(ID)}; db.delete(GameMetaData.GamePlay.table_name,whereClause,whereArgs); db.close(); } //更新 *** 作 public voID update(GamePlayer gamePlayer) { sqliteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(GameMetaData.GamePlay.PLAYER,gamePlayer.getLevel()); String whereClause = GameMetaData.GamePlay._ID + "=?"; String[] whereArgs = {String.valueOf(gamePlayer.getID())}; db.update(GameMetaData.GamePlay.table_name,values,whereArgs); db.close(); } //查询 public GamePlayer findByID(int ID) { sqliteDatabase db = dbHelper.getReadableDatabase(); Cursor cursor = db.query(true,GameMetaData.GamePlay.table_name,GameMetaData.GamePlay._ID + "=?", new String[]{String.valueOf(ID)},null); GamePlayer gamePlayer = null; if (cursor.movetoNext()) { gamePlayer = new GamePlayer(); gamePlayer.setPlayer(cursor.getString(cursor.getColumnIndexOrThrow(GameMetaData.GamePlay.PLAYER))); gamePlayer.setID(cursor.getInt(cursor.getColumnIndexOrThrow(GameMetaData.GamePlay._ID))); gamePlayer.setLevel(cursor.getInt(cursor.getColumnIndexOrThrow(GameMetaData.GamePlay.LEVEL))); gamePlayer.setscore(cursor.getInt(cursor.getColumnIndexOrThrow(GameMetaData.GamePlay.score))); } cursor.close(); db.close(); return gamePlayer; } public ArrayList<GamePlayer> findAll() { String sql = "select _ID,player,score,level from player_table order by score desc"; sqliteDatabase db = dbHelper.getReadableDatabase(); Cursor c = db.rawquery(sql,null); ArrayList<GamePlayer> gamePlayers = new ArrayList<>(); GamePlayer gamePlayer = null; while (c.movetoNext()) { gamePlayer = new GamePlayer(); gamePlayer.setPlayer(c.getString(c.getColumnIndexOrThrow(GameMetaData.GamePlay.PLAYER))); gamePlayer.setID(c.getInt(c.getColumnIndexOrThrow(GameMetaData.GamePlay._ID))); gamePlayer.setscore(c.getInt(c.getColumnIndexOrThrow(GameMetaData.GamePlay.score))); gamePlayer.setLevel(c.getInt(c.getColumnIndexOrThrow(GameMetaData.GamePlay.LEVEL))); gamePlayers.add(gamePlayer); } c.close(); db.close(); return gamePlayers; } //查询总记录数 public int getCount() { int count = 0; String sql = "select count(_ID) from player_table"; sqliteDatabase db = dbHelper.getReadableDatabase(); Cursor c = db.rawquery(sql,null); c.movetoFirst(); count = c.getInt(0);//取第一条 c.close(); db.close(); return count; }}DatabaseHelper
public class DatabaseHelper extends sqliteOpenHelper { private static final String DB_name = "game.db"; private static final int VERSION = 1; //创建表 sql private static final String CREATE_table_PLAYER = "CREATE table IF NOT EXISTS player_table(" + "_ID INTEGER PRIMARY KEY autoINCREMENT," + "player TEXT,score INTEGER,level INTEGER)"; //删除表 private static final String DROP_table_PLAYER = "DROP table IF EXISTS player_table"; public DatabaseHelper(Context context) { super(context,DB_name,VERSION); } @OverrIDe public voID onCreate(sqliteDatabase db) { db.execsql(CREATE_table_PLAYER); } @OverrIDe public voID onUpgrade(sqliteDatabase db,int oldVersion,int newVersion) { db.execsql(DROP_table_PLAYER); db.execsql(CREATE_table_PLAYER); }}3.以Fragment的形式呈现并完善功能,创建Fragment存放用到的Fragment(AddFragment GamePlayFragment UpdateFragment)
AddFragment用于完成添加游戏玩家功能,这里利用d窗的形式,和菜单
activity.xml为空
menu_main1229
<menu xmlns:androID="http://schemas.androID.com/apk/res/androID" xmlns:app="http://schemas.androID.com/apk/res-auto" xmlns:tools="http://schemas.androID.com/tools" tools:context=".Main1229Activity"> <item androID:ID="@+ID/add" androID:Title="@string/add" androID:icon="@androID:drawable/ic_menu_add" androID:orderIncategory="100" app:showAsAction="always" /></menu>AddFragment
public class AddFragment extends DialogFragment { private AddFragmentListener addFragmentListener; //定义接口,方便与activity交互 : public static interface AddFragmentListener { public voID add(GamePlayer gamePlayer); } public AddFragment(){ } //获取 主页面的activity @OverrIDe public voID onAttach(Activity activity) { super.onAttach(activity); try { addFragmentListener = (AddFragmentListener) activity; } catch (ClassCastException e) { e.printstacktrace(); } } //保证 activity 给 fragment 传参时,旋转屏幕参数不丢失 public static AddFragment newInstance() { AddFragment frag = new AddFragment(); return frag; } @OverrIDe public Dialog onCreateDialog(Bundle savedInstanceState) { //定义一个对话框视图 final VIEw vIEw = LayoutInflater.from(getActivity()).inflate(R.layout.create_game_dialog,null); return new AlertDialog.Builder(getActivity()) .setIcon(androID.R.drawable.ic_input_add) .setVIEw(vIEw) .setTitle("新增游戏玩家") .setPositivebutton("保存", new DialogInterface.OnClickListener() { public voID onClick(DialogInterface dialog,int whichbutton) { //获取界面 组件对象 EditText et_player = (EditText) vIEw.findVIEwByID(R.ID.editText2_player); EditText et_score = (EditText) vIEw.findVIEwByID(R.ID.editText_cscore); EditText et_level = (EditText) vIEw.findVIEwByID(R.ID.edit_level); //接收用户的输入填充对象 GamePlayer gamePlayer = new GamePlayer(); gamePlayer.setPlayer(et_player.getText().toString()); gamePlayer.setscore(Integer.parseInt(et_score.getText().toString())); gamePlayer.setLevel(Integer.parseInt(et_level.getText().toString())); addFragmentListener.add(gamePlayer);//调用activity方法 进行数据库添加 *** 作 dialog.dismiss(); } } ) .setNegativebutton("取消",new DialogInterface.OnClickListener() { public voID onClick(DialogInterface dialog,int which) { dialog.dismiss();//隐藏对话框 } }).create(); }}create_game_dialog.xml
<?xml version="1.0" enCoding="utf-8"?><linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID" androID:layout_wIDth="match_parent" androID:layout_height="match_parent" androID:orIEntation="vertical" androID:weightSum="1"> <EditText androID:layout_wIDth="match_parent" androID:layout_height="wrap_content" androID:ID="@+ID/editText2_player" androID:hint="请输入玩家名称" /> <EditText androID:layout_wIDth="match_parent" androID:layout_height="wrap_content" androID:ID="@+ID/editText_cscore" androID:hint="请输入玩家分数" /> <EditText androID:layout_wIDth="match_parent" androID:layout_height="wrap_content" androID:ID="@+ID/edit_level" androID:hint="请输入玩家关卡数" /></linearLayout>GamePlayFragment 完成玩家信息的现实及触发更改等内容
Fragment_game_play.xml
<FrameLayout xmlns:androID="http://schemas.androID.com/apk/res/androID" xmlns:tools="http://schemas.androID.com/tools" androID:layout_wIDth="match_parent" androID:layout_height="match_parent" tools:context="com.jin.administrator.my1229application.fragment.GamePlayFragment"> <!--数据列表显示容器--> <ListVIEw androID:layout_wIDth="match_parent" androID:layout_height="match_parent" androID:ID="@+ID/ListVIEw" androID:layout_gravity="center" androID:choiceMode="none" /></FrameLayout>game_player_List_item_layout.xml(显示玩家信息数据)
<?xml version="1.0" enCoding="utf-8"?><relativeLayout xmlns:androID="http://schemas.androID.com/apk/res/androID" androID:layout_wIDth="match_parent" androID:layout_height="match_parent" > <TextVIEw androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:textAppearance="?androID:attr/textAppearanceSmall" androID:text="序号:" androID:ID="@+ID/textVIEw" /> <TextVIEw androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:textAppearance="?androID:attr/textAppearanceSmall" androID:text="玩家:" androID:ID="@+ID/textVIEw2" androID:layout_below="@+ID/textVIEw" androID:layout_alignParentleft="true" androID:layout_alignParentStart="true" /> <TextVIEw androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:textAppearance="?androID:attr/textAppearanceSmall" androID:text="分数:" androID:ID="@+ID/textVIEw3" androID:layout_below="@+ID/textVIEw2" androID:layout_alignParentleft="true" androID:layout_alignParentStart="true" /> <TextVIEw androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:textAppearance="?androID:attr/textAppearanceSmall" androID:text="关卡:" androID:ID="@+ID/textVIEw4" androID:layout_below="@+ID/textVIEw3" androID:layout_alignParentleft="true" androID:layout_alignParentStart="true" /> <TextVIEw androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:hint="not data" androID:textAppearance="?androID:attr/textAppearanceSmall" androID:ID="@+ID/textVIEw_ID" androID:layout_alignParenttop="true" androID:layout_toRightOf="@+ID/textVIEw" androID:layout_toEndOf="@+ID/textVIEw" /> <TextVIEw androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:hint="not data" androID:textAppearance="?androID:attr/textAppearanceSmall" androID:ID="@+ID/textVIEw_player" androID:layout_below="@+ID/textVIEw" androID:layout_toRightOf="@+ID/textVIEw" androID:layout_toEndOf="@+ID/textVIEw" /> <TextVIEw androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:hint="not data" androID:textAppearance="?androID:attr/textAppearanceSmall" androID:ID="@+ID/textVIEw_score" androID:layout_below="@+ID/textVIEw2" androID:layout_toRightOf="@+ID/textVIEw2" androID:layout_toEndOf="@+ID/textVIEw2" /> <TextVIEw androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:hint="not data" androID:textAppearance="?androID:attr/textAppearanceSmall" androID:ID="@+ID/textVIEw_level" androID:layout_toRightOf="@+ID/textVIEw3" androID:layout_toEndOf="@+ID/textVIEw3" androID:layout_below="@+ID/textVIEw_score"/></relativeLayout>ListvIEw_content_mrnu.xml(d窗上面的menu)
<?xml version="1.0" enCoding="utf-8"?><menu xmlns:androID="http://schemas.androID.com/apk/res/androID"> <item androID:ID="@+ID/delete_menu" androID:orderIncategory="100" androID:Title="删除" androID:icon="@androID:drawable/ic_menu_delete"/> <item androID:ID="@+ID/update_menu" androID:orderIncategory="100" androID:Title="修改" androID:icon="@androID:drawable/ic_menu_edit"/></menu>GamePlayFragment
public class GamePlayFragment extends Fragment { //适配器对象 GamePlayerAdapter gamePlayerAdapter; //接口对象 private GamePlayerFragmentListener gamePlayerFragmentListener; //定义接口 public static interface GamePlayerFragmentListener { public voID showGamePlayerFragment();//作用:显示列表 界面 public voID showUpdateFragment(int ID);//作用:更新数据的 从当前页面到更新页面,需要将本页的ID带到更新页面上去 界面 public voID delete(int ID); public ArrayList<GamePlayer> findAll(); } //保证 activity 给 fragment 传参时,旋转屏幕参数不丢失 public static GamePlayFragment newInstance() { GamePlayFragment fragment = new GamePlayFragment(); return fragment; } public GamePlayFragment(){ } //获取 主页面的activity @OverrIDe public voID onAttach(Activity activity) { super.onAttach(activity); try { gamePlayerFragmentListener = (GamePlayerFragmentListener) activity; } catch (ClassCastException e) { e.printstacktrace(); } } /**************长按 每个item 时d出菜单 ***********************************/ /** * 创建 菜单项 */ @OverrIDe public voID onCreateContextMenu(ContextMenu menu,VIEw v,ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu,v,menuInfo); menu.setheaderTitle("修改/删除");//菜单标题 menu.setheaderIcon(androID.R.drawable.ic_menu_edit); //实例化 菜单项 getActivity().getMenuInflater().inflate(R.menu.ListvIEw_context_menu,menu); } @OverrIDe public boolean onContextItemSelected(MenuItem item) { switch (item.getItemID()) { case R.ID.delete_menu: //获取菜单 信息对象 AdapterVIEw.AdapterContextMenuInfo info = (AdapterVIEw.AdapterContextMenuInfo) item.getMenuInfo(); //获取前当前item的指定组件, targetVIEw :当前点击的item视图 TextVIEw textVIEw_ID = (TextVIEw) info.targetVIEw.findVIEwByID(R.ID.textVIEw_ID); //获取组件上的内容,即ID int ID = Integer.parseInt(textVIEw_ID.getText().toString()); //调用 activity的删除方法,删除指定的 ID 数据 gamePlayerFragmentListener.delete(ID); //重新查询视图列表数据 changeData(); break; case R.ID.update_menu: info = (AdapterVIEw.AdapterContextMenuInfo) item.getMenuInfo(); textVIEw_ID = (TextVIEw) info.targetVIEw.findVIEwByID(R.ID.textVIEw_ID); ID = Integer.parseInt(textVIEw_ID.getText().toString()); //调用 activity的更新方法,显示更新的视图 gamePlayerFragmentListener.showUpdateFragment(ID); break; } return super.onContextItemSelected(item); } /************************显示列表 fragment 实例会调以下方法*************************/ /** * 在这里实例化 适配器对象,并填充数据 */ @OverrIDe public voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //从数据库中获取列表数据 ArrayList<GamePlayer> gamePlayers = gamePlayerFragmentListener.findAll(); //实例化 适配器 gamePlayerAdapter = new GamePlayerAdapter(getActivity(),gamePlayers); } /** * 自定义 ListVIEw布局 */ @OverrIDe public VIEw onCreateVIEw(LayoutInflater inflater,VIEwGroup container, Bundle savedInstanceState) { //实例化 fragment布局 VIEw vIEw = inflater.inflate(R.layout.fragment_game_play,container,false); ListVIEw ListVIEw = (ListVIEw) vIEw.findVIEwByID(R.ID.ListVIEw); //注册上下文,因为长按时,要d出菜单 registerForContextMenu(ListVIEw); // 自定义布局 ListVIEw.setAdapter(gamePlayerAdapter);//设置 适配器 return vIEw; } //自定义适配器 private static class GamePlayerAdapter extends BaseAdapter { private Context context; //列表 数据 private ArrayList<GamePlayer> gamePlayers; //重新设置 public voID setGamePlayers(ArrayList<GamePlayer> gamePlayers) { this.gamePlayers = gamePlayers; } public GamePlayerAdapter(Context context,ArrayList<GamePlayer> gamePlayers) { this.context = context; this.gamePlayers = gamePlayers; } @OverrIDe public int getCount() { return gamePlayers.size(); } @OverrIDe public Object getItem(int position) { return gamePlayers.get(position); } @OverrIDe public long getItemID(int position) { return position; } @OverrIDe public VIEw getVIEw(int position,VIEw convertVIEw,VIEwGroup parent) { //节省性能,使用VIEwHolder减少对象的查找 VIEwHolder vh = null; if (convertVIEw == null) {//convertVIEw:缓存item 减少对象的创建 //实例化 item 布局 convertVIEw=LayoutInflater.from(context).inflate(R.layout.game_player_List_item_layout,null); vh = new VIEwHolder(); vh.tv_ID = (TextVIEw) convertVIEw.findVIEwByID(R.ID.textVIEw_ID); vh.tv_player = (TextVIEw) convertVIEw.findVIEwByID(R.ID.textVIEw_player); vh.tv_score = (TextVIEw) convertVIEw.findVIEwByID(R.ID.textVIEw_score); vh.tv_level = (TextVIEw) convertVIEw.findVIEwByID(R.ID.textVIEw_level); convertVIEw.setTag(vh); } else { vh = (VIEwHolder) convertVIEw.getTag(); } //组件数据填充 GamePlayer g = gamePlayers.get(position); vh.tv_ID.setText(String.valueOf(g.getID())); vh.tv_player.setText(g.getPlayer()); vh.tv_score.setText(String.valueOf(g.getscore())); vh.tv_level.setText(String.valueOf(g.getLevel())); return convertVIEw; } } //用于保存每一次查找的组件,避免下次重复查找 private static class VIEwHolder { TextVIEw tv_ID; TextVIEw tv_player; TextVIEw tv_score; TextVIEw tv_level; } //重新查询数据 public voID changeData() { //从数据库查询数据,并填充到适配器中 gamePlayerAdapter.setGamePlayers(gamePlayerFragmentListener.findAll()); //让适配器重新加载数据 ,通知视内容更变 gamePlayerAdapter.notifyDataSetChanged(); } /** * 销毁时,置空 */ @OverrIDe public voID onDetach() { super.onDetach(); gamePlayerFragmentListener = null; }}UpdateFragment (完成数据的更新)
fragment_update.xml
<relativeLayout androID:ID="@+ID/relative_layout" xmlns:androID="http://schemas.androID.com/apk/res/androID" xmlns:tools="http://schemas.androID.com/tools" androID:layout_wIDth="match_parent" androID:layout_height="match_parent" tools:context="Fragments.UpdateFragment" > <TextVIEw androID:ID="@+ID/textVIEw1_ID" androID:layout_wIDth="wrap_content" androID:layout_height="50dp" androID:gravity="center" androID:textSize="20sp" androID:layout_gravity="left|top" androID:text="序号:"/> <TextVIEw androID:ID="@+ID/textVIEw1_player" androID:layout_wIDth="wrap_content" androID:layout_height="50dp" androID:gravity="center" androID:textSize="20sp" androID:layout_below="@+ID/textVIEw1_ID" androID:text="玩家:" /> <EditText androID:ID="@+ID/editText2_player" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:layout_toRightOf="@+ID/textVIEw1_player" androID:layout_aligntop="@+ID/textVIEw1_player" androID:layout_alignBottom="@+ID/textVIEw1_player" androID:hint="请输入玩家名称" /> <TextVIEw androID:ID="@+ID/textVIEw1_score" androID:layout_wIDth="wrap_content" androID:layout_height="50dp" androID:gravity="center" androID:textSize="20sp" androID:layout_below="@+ID/editText2_player" androID:text="分数:"/> <EditText androID:ID="@+ID/editText2_score" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:layout_below="@+ID/editText2_player" androID:layout_toRightOf="@+ID/textVIEw1_player" androID:hint="请输入玩家分数" /> <TextVIEw androID:ID="@+ID/textVIEw1_level" androID:layout_wIDth="wrap_content" androID:layout_height="50dp" androID:gravity="center" androID:textSize="20sp" androID:layout_below="@+ID/editText2_score" androID:text="关卡:"/> <EditText androID:ID="@+ID/editText2_level" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:layout_below="@+ID/editText2_score" androID:layout_toRightOf="@+ID/textVIEw1_player" androID:hint="请输入关卡数" /> <TextVIEw androID:ID="@+ID/textVIEw2_ID" androID:layout_wIDth="wrap_content" androID:layout_height="50dp" androID:gravity="center" androID:textSize="20sp" androID:layout_alignParenttop="true" androID:layout_toRightOf="@+ID/textVIEw1_ID"/> <TextVIEw androID:ID="@+ID/textVIEw_into" androID:layout_wIDth="wrap_content" androID:layout_height="50dp" androID:gravity="center" androID:textSize="20sp" androID:layout_alignParentBottom="true" androID:layout_marginBottom="115dp" androID:text="提示:这里为更新信息"/> <linearLayout androID:layout_wIDth="match_parent" androID:layout_height="wrap_content" androID:layout_alignParentBottom="true" androID:orIEntation="horizontal"> <button androID:ID="@+ID/button_save" androID:layout_wIDth="0dp" androID:layout_height="wrap_content" androID:layout_alignParentBottom="true" androID:layout_weight="1" androID:text="更新" /> <button androID:ID="@+ID/button_cancel" androID:layout_wIDth="0dp" androID:layout_height="wrap_content" androID:layout_alignBottom="@+ID/button_save" androID:layout_weight="1" androID:text="取消" /> </linearLayout></relativeLayout>UpdateFragment
public class UpdateFragment extends Fragment implements VIEw.OnClickListener { private EditText et_player; private EditText et_score; private EditText et_level; private GamePlayer gamePlayer; //activity 实现的接口 private UpdateFragmentListener updateFragmentListener; //定义接口 public static interface UpdateFragmentListener { public GamePlayer findByID(int ID); //作用:查询 public voID update(GamePlayer gamePlayer);//作用:更新 } @OverrIDe public voID onAttach(Activity activity) { super.onAttach(activity); try { updateFragmentListener = (UpdateFragmentListener) activity; } catch (ClassCastException e) { e.printstacktrace(); } } //保证 activity 给 fragment 传参时,旋转屏幕参数不丢失 public static UpdateFragment newInstance(int ID) { UpdateFragment updateFragment = new UpdateFragment(); Bundle b = new Bundle(); b.putInt("ID",ID); updateFragment.setArguments(b);//保存传入的参数 return updateFragment; } /*******************实例化 fragment 时,调用以下方法****************************/ /** * 实例化时 查询数据 */ @OverrIDe public voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); int ID = getArguments().getInt("ID"); //activity 从数据库中查询指定ID的对象数据 gamePlayer = updateFragmentListener.findByID(ID); } @OverrIDe public VIEw onCreateVIEw(LayoutInflater inflater, Bundle savedInstanceState) { //实例化 fragment布局 VIEw vIEw = inflater.inflate(R.layout.fragment_update,false); //查找界面 组件 TextVIEw tv_ID = (TextVIEw) vIEw.findVIEwByID(R.ID.textVIEw2_ID); et_player = (EditText) vIEw.findVIEwByID(R.ID.editText2_player); et_score = (EditText) vIEw.findVIEwByID(R.ID.editText2_score); et_level = (EditText) vIEw.findVIEwByID(R.ID.editText2_level); //界面按钮 button button_save = (button) vIEw.findVIEwByID(R.ID.button_save); button button_cancel = (button) vIEw.findVIEwByID(R.ID.button_cancel); //注册监听事件 button_save.setonClickListener(this); button_cancel.setonClickListener(this); //组件内容填充 tv_ID.setText(String.valueOf(gamePlayer.getID())); et_player.setText(gamePlayer.getPlayer()); et_score.setText(String.valueOf(gamePlayer.getscore())); et_level.setText(String.valueOf(gamePlayer.getLevel())); return vIEw; } /**************** fragment 上按钮的监听事件 *************************/ /** * 按钮 监听事件 * * @param v */ @OverrIDe public voID onClick(VIEw v) { switch (v.getID()) { case R.ID.button_save: save(); break; case R.ID.button_cancel: getActivity().getFragmentManager().popBackStack();//d出 栈 break; } } //数据提交到数据库 private voID save() { GamePlayer g = new GamePlayer(); //组件的输入内容添加 到数据库中 g.setID(gamePlayer.getID()); g.setPlayer(et_player.getText().toString()); g.setscore(Integer.parseInt(et_score.getText().toString())); g.setLevel(Integer.parseInt(et_level.getText().toString())); //调用 activity中的更新方法 updateFragmentListener.update(g); getActivity().getFragmentManager().popBackStack(); //出栈 } @OverrIDe public voID onDetach() { super.onDetach(); updateFragmentListener = null; }}最后MainActivity(完成跟Fragment之间的交互及数据库方法)
mainActivity.xml(装Fragment)
<relativeLayout xmlns:androID="http://schemas.androID.com/apk/res/androID" xmlns:tools="http://schemas.androID.com/tools" androID:layout_wIDth="match_parent" androID:layout_height="match_parent" androID:paddingleft="@dimen/activity_horizontal_margin" androID:paddingRight="@dimen/activity_horizontal_margin" androID:paddingtop="@dimen/activity_vertical_margin" androID:paddingBottom="@dimen/activity_vertical_margin" tools:context=".Main1229Activity"> <FrameLayout androID:layout_wIDth="match_parent" androID:layout_height="match_parent" androID:ID="@+ID/main_layout"/></relativeLayout>MainActivity
public class Main1229Activity extends AppCompatActivity implements AddFragment.AddFragmentListener, GamePlayFragment.GamePlayerFragmentListener,UpdateFragment.UpdateFragmentListener{ // *** 作数据库 private DatabaseAdapter dbAdapter; //要交互的 fragment private GamePlayFragment gamePlayerFragment; //显示数据界面 private UpdateFragment updateFragment; //更新数据界面 @OverrIDe protected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.activity_main1229); dbAdapter = new DatabaseAdapter(this);//实例化 *** 作数据库类 //显示列表数据 showGamePlayerFragment(); } /** * 实例化菜单 布局 */ @OverrIDe public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main1229,menu); return true; } /** * 当点击菜单项按钮时触发 */ @OverrIDe public boolean onoptionsItemSelected(MenuItem item) { int ID = item.getItemID(); switch (ID) { case R.ID.add://添加按钮的 *** 作 AddFragment createGamePlayerFragment=AddFragment.newInstance(); createGamePlayerFragment.show(getFragmentManager(),null); break; } return super.onoptionsItemSelected(item); } //添加 @OverrIDe public voID add(GamePlayer gamePlayer) { dbAdapter.add(gamePlayer); gamePlayerFragment.changeData();//添加后,重新加载数据 } //显示列表 @OverrIDe public voID showGamePlayerFragment() { //获取 显示数据列表的fragment对象 gamePlayerFragment = GamePlayFragment.newInstance();// 会调用:onCreateVIEw方法 //开启事务 FragmentTransaction ft = getFragmentManager().beginTransaction(); //将 activity 中的布局文件 替换成 fragment ft.replace(R.ID.main_layout,gamePlayerFragment); ft.addToBackStack(null); ft.commit(); } //显示更新fragment @OverrIDe public voID showUpdateFragment(int ID) { updateFragment = UpdateFragment.newInstance(ID); FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.ID.main_layout,updateFragment); ft.addToBackStack(null); ft.commit(); } //删除 @OverrIDe public voID delete(int ID) { dbAdapter.delete(ID); gamePlayerFragment.changeData();//删除后 重新加载数据 } //查找所有 @OverrIDe public ArrayList<GamePlayer> findAll() { return dbAdapter.findAll(); } //查找一个 @OverrIDe public GamePlayer findByID(int ID) { return dbAdapter.findByID(ID); } //更新数据 @OverrIDe public voID update(GamePlayer gamePlayer) { dbAdapter.update(gamePlayer); gamePlayerFragment.changeData();//更新后 重新加载数据 } /****************手机按键 监听事件*******************************/ @OverrIDe public boolean onKeyDown(int keyCode,KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK){ if(getFragmentManager().getBackStackEntryCount()==1){//当 栈中只是一个fragment时,就结束程序 finish(); return true; }else { getFragmentManager().popBackStack(); return true; } } return super.onKeyDown(keyCode,event); }}六丶小总结
1.熟悉掌握了sqlite的基本用法
2.加强了Fragment与Activity的交互
3.由于刚入门开始借用了有很多小错误的代码,找BUG各种挣扎,拖到现在才完成对于本节的学习
总结以上是内存溢出为你收集整理的玩家信息管理(SQLite+Fragment加强)全部内容,希望文章能够帮你解决玩家信息管理(SQLite+Fragment加强)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)