android---(数据库实践)

这里写图片描述

这里写图片描述

数据库实践
db

/**
 * 数据库表 所对应实体
 */
public class GamePlayer {

    private String player;
    private int score;
    private int level;
    private int id;

    public GamePlayer() {
    }

    public GamePlayer(int level, String player, int score) {
        this.level = level;
        this.player = player;
        this.score = score;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getLevel() {
        return level;
    }

    public void setLevel(int level) {
        this.level = level;
    }

    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;
    }

    @Override
    public String toString() {
        return "GamePlayer{" +
                "id=" + id +
                ", player='" + player + '\'' +
                ", score=" + score +
                ", level=" + level +
                '}';
    }
}
/**
 * 数据库元数据
 */
public 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";
    }
}
/**
 * 数据库 助手类
 */
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, null, 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);
    }
}
/**
 *  数据库操作 CRUD
 */
public class DatabaseAdapter {

    private DatabaseHelper dbHelper = null;

    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.getPlayer());

        String whereClause = GameMetaData.GamePlay._ID + "=?";
        String[] whereArgs = {String.valueOf(gamePlayer.getId())};
        db.update(GameMetaData.GamePlay.TABLE_NAME, values, whereClause, whereArgs);
        db.close();
    }

    //查询
    public GamePlayer findById(int id) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();


        Cursor cursor = db.query(true, GameMetaData.GamePlay.TABLE_NAME, null, GameMetaData.GamePlay._ID + "=?",
                new String[]{String.valueOf(id)}, null, null, null, null);

        GamePlayer player = null;
        if (cursor.moveToNext()) {
            player = new GamePlayer();

            player.setPlayer(cursor.getString(cursor.getColumnIndexOrThrow(GameMetaData.GamePlay.PLAYER)));
            player.setId(cursor.getInt(cursor.getColumnIndexOrThrow(GameMetaData.GamePlay._ID)));
            player.setLevel(cursor.getInt(cursor.getColumnIndexOrThrow(GameMetaData.GamePlay.LEVEL)));
            player.setScore(cursor.getInt(cursor.getColumnIndexOrThrow(GameMetaData.GamePlay.SCORE)));
        }
        cursor.close();
        db.close();
        return player;
    }


    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;
    }

}

activity类

/**
 * 程序入口
 * <p/>
 * 分析:
 * 1.有哪些功能
 * 2.在哪些界面上
 * 3.将相应的功能方法在相应的界面进行定义
 * 4.在主界面实现接口方法,用于不现界面之间的交互
 */
public class MainActivity extends AppCompatActivity implements AddFragment.AddFragmentListener, GamePlayFragment.GamePlayerFragmentListener, UpdateFragment.UpdateFragmentListener {

    //操作数据库
    private DatabaseAdapter dbAdapter;

    //要交互的 fragment
    private AddFragment addFragment; //添加数据界面
    private GamePlayFragment gamePlayFragment; //显示数据界面
    private UpdateFragment updateFragment; //更新数据界面


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dbAdapter = new DatabaseAdapter(this);//实例化操作数据库类类

        //显示列表数据
        showGamePlayerFragment();
    }

    /**
     * 实例化菜单 布局
     *
     * @param menu
     * @return
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    /**
     * 当点击菜单项按钮时触发
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.add://添加按钮的操作
                addFragment = AddFragment.newInstance();//显示添加界面
                addFragment.show(getFragmentManager(), null);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    //添加
    @Override
    public void add(GamePlayer gamePlayer) {
        dbAdapter.add(gamePlayer);
        gamePlayFragment.changeData();//添加后,重新加载数据
    }

    //显示列表
    @Override
    public void showGamePlayerFragment() {

        //获取 显示数据列表的fragment对象
        gamePlayFragment = GamePlayFragment.newInstance();// 会调用:onCreateView方法

        //开启事务
        FragmentTransaction ft = getFragmentManager().beginTransaction();

        //将 activity 中的布局文件 替换成 fragment
        ft.replace(R.id.main_layout, gamePlayFragment);

        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);
        gamePlayFragment.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);
        gamePlayFragment.changeData();//更新后 重新加载数据

    }


    /****************手机按键 监听事件*******************************/
    /**
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK){
            if(getFragmentManager().getBackStackEntryCount()==1){//当 栈中只是一个fragment时,就结束程序
                finish();
            }else {
                getFragmentManager().popBackStack();
                return true;
            }
        }

        return super.onKeyDown(keyCode, event);
    }
}
--------------------------
activity.xml
<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:paddingBottom="@dimen/activity_vertical_margin"
                android:paddingLeft="@dimen/activity_horizontal_margin"
                android:paddingRight="@dimen/activity_horizontal_margin"
                android:paddingTop="@dimen/activity_vertical_margin"
                tools:context=".MainActivity">

    <FrameLayout
        android:id="@+id/main_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
    </FrameLayout>

</RelativeLayout>

--------------------------------
item布局
<?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"
    >

    <TextView
        android:id="@+id/textView1_id"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="New Text"/>

    <TextView
        android:id="@+id/textView1_player"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="New Text"/>

    <TextView
        android:id="@+id/textView_score"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="New Text"/>

    <TextView
        android:id="@+id/textView_level"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="New Text"/>
</LinearLayout>

fragments

addFragment:
/**
 * 添加Fragment:弹出对话框的方式实现添加
 */
public class AddFragment extends DialogFragment {

    AddFragmentListener addFragmentListener;


    //定义接口,方便与activity交互 :
    public static interface AddFragmentListener {
        public void add(GamePlayer gamePlayer);
    }

    //获取 主页面的activity
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            addFragmentListener = (AddFragmentListener) context;
        } catch (ClassCastException e) {
            e.printStackTrace();
        }

    }

    //保证 activity 给 fragment 传参时,旋转屏幕参数不丢失
    public static AddFragment newInstance() {
        AddFragment addFragment = new AddFragment();
        return addFragment;
    }

/************添加 fragment 实例时,会调用以下的方法**********************/
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_add, container, false);
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        /**
         *  1. 将对话框的布局实例化出来
         *  2. 创建弹出对话框
         */

        //定义一个对话框视图
        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() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //获取界面 组件对象
                        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() {
                    @Override
                    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>

---------------
fragment_add.xml
空

/**
 *  显示数据列表、长按item 弹出对话框
 */
public class GamePlayFragment extends Fragment {

    //适配器对象
    GamePlayerAdapter gamePlayerAdapter;

    //接口对象
    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
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            gamePlayerFragmentListener = (GamePlayerFragmentListener) context;
        } catch (ClassCastException e) {
            e.printStackTrace();
        }

    }


    //保证 activity 给 fragment 传参时,旋转屏幕参数不丢失
    public static GamePlayFragment newInstance() {
        GamePlayFragment gamePlayFragment = new GamePlayFragment();
        return gamePlayFragment;
    }

    /************************显示列表 fragment 实例会调以下方法*************************/
    /**
     * 在这里实例化 适配器对象,并填充数据
     *
     * @param savedInstanceState
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //从数据库中获取列表数据
        ArrayList<GamePlayer> gamePlayers = gamePlayerFragmentListener.findAll();

        //实例化 适配器
        gamePlayerAdapter = new GamePlayerAdapter(getActivity(), gamePlayers);
    }


    /**
     * 自定义 listView布局
     *
     * @param inflater
     * @param container
     * @param savedInstanceState
     * @return
     */
    @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);

        //注册上下文,因为长按时,要弹出菜单
        registerForContextMenu(listView);

        //        自定义布局
        listView.setAdapter(gamePlayerAdapter);//设置 适配器
        return view;
    }


    //自定义适配器
    private static class GamePlayerAdapter extends BaseAdapter {

        private Context context;

        //列表 数据
        private ArrayList<GamePlayer> gamePlayers;

        public GamePlayerAdapter(Context context, ArrayList<GamePlayer> gamePlayers) {
            this.context = context;
            this.gamePlayers = gamePlayers;
        }

        //重新设置
        public void setGamePlayers(ArrayList<GamePlayer> gamePlayers) {
            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 布局
                LayoutInflater.from(context).inflate(R.layout.game_player_list_item_layout, null);

                vh = new ViewHolder();
                vh.tv_id = (TextView) convertView.findViewById(R.id.textView1_id);
                vh.tv_player = (TextView) convertView.findViewById(R.id.textView1_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(g.getScore());
            vh.tv_level.setText(g.getLevel());

            return convertView;
        }
    }


    //用于保存每一次查找的组件,避免下次重复查找
    private static class ViewHolder {
        TextView tv_id;
        TextView tv_player;
        TextView tv_score;
        TextView tv_level;
    }


    /**************长按 每个item 时弹出菜单 ***********************************/
    /**
     * 创建 菜单项
     *
     * @param menu
     * @param v
     * @param menuInfo
     */
    @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.textView1_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.textView1_id);

                id = Integer.parseInt(textView_id.getText().toString());

                //调用 activity的更新方法,显示更新的视图
                gamePlayerFragmentListener.showUpdateFragment(id);
                break;
        }
        return super.onContextItemSelected(item);
    }

    //重新查询数据
    public void changeData() {
        //从数据库查询数据,并填充到适配器中
        gamePlayerAdapter.setGamePlayers(gamePlayerFragmentListener.findAll());

        //让适配器重新加载数据 ,通知视内容更变
        gamePlayerAdapter.notifyDataSetChanged();

    }


    /**
     * 销毁时,置空
     */
    @Override
    public void onDetach() {
        super.onDetach();
        gamePlayerFragmentListener = null;
    }
}

------------------------------------
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="Fragments.GamePlayFragment">


    <!--数据列表显示容器-->
    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/listView"
        android:layout_gravity="center"
        android:choiceMode="none"
        />
</FrameLayout>
public class UpdateFragment extends Fragment implements View.OnClickListener {

    private EditText et_player;
    private EditText et_score;
    private EditText et_level;

    private GamePlayer gamePlayer;

    //activity 实现的接口
    UpdateFragmentListener updateFragmentListener;


    //定义接口
    public static interface UpdateFragmentListener {
        public GamePlayer findById(int id); //作用:查询

        public void update(GamePlayer gamePlayer);//作用:更新
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            updateFragmentListener = (UpdateFragmentListener) context;
        } 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 时,调用以下方法****************************/
    /**
     * 实例化时 查询数据
     *
     * @param savedInstanceState
     */
    @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, ViewGroup container,
                             Bundle savedInstanceState) {

        //实例化 fragment布局
        View view = inflater.inflate(R.layout.fragment_update, container, 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();//弹出 栈
                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;
    }
}

更新 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="wrap_content"
        android:layout_gravity="left|top"
        android:text="序号:"/>

    <TextView
        android:id="@+id/textView1_player"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        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_alignParentEnd="true"
        android:layout_alignTop="@+id/textView1_player"
        android:layout_toEndOf="@+id/textView1_player"
        android:hint="请输入玩家名称"
        />

    <TextView
        android:id="@+id/textView1_score"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        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_alignEnd="@+id/editText2_player"
        android:layout_alignStart="@+id/editText2_player"
        android:layout_below="@+id/editText2_player"
        android:hint="请输入玩家分数"
        />

    <TextView
        android:id="@+id/textView1_level"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        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_alignParentEnd="true"
        android:layout_alignStart="@+id/editText2_score"
        android:layout_below="@+id/editText2_score"
        android:hint="请输入关卡数"
        />

    <TextView
        android:id="@+id/textView2_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentTop="true"
        android:layout_toEndOf="@+id/textView1_player"/>

    <TextView
        android:id="@+id/textView_into"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignEnd="@+id/editText2_level"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true"
        android:layout_marginBottom="115dp"
        android:text="提示:这里为更新信息"/>


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="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_alignParentStart="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>
--------------------
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值