zoukankan      html  css  js  c++  java
  • android 35 ListView增删改差

    MainActivity

    package com.sxt.day05_11;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.content.DialogInterface.OnClickListener;
    import android.os.Bundle;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemLongClickListener;
    import android.widget.BaseAdapter;
    import android.widget.ImageView;
    import android.widget.ListView;
    import android.widget.TextView;
    
    import com.sxt.day05_11.entity.GeneralBean;
    
    public class MainActivity extends Activity {
        ListView mlvGeneral;
        List<GeneralBean> mGenerals;
        GeneralAdapter mAdapter;
        private static final int ACTION_DETAILS=0;
        private static final int ACTION_ADD=1;
        private static final int ACTION_DELETE=2;
        private static final int ACTION_UPDATE=3;
    
        int mPosition;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            initData();
            initView();
            setListener();
        }
    
        private void setListener() {
            mlvGeneral.setOnItemLongClickListener(new OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> parent, View view,
                        final int position, long id) {
                    AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle("选择以下操作")
                        .setItems(new String[]{"查看详情","添加数据","删除数据","修改数据"}, new OnClickListener() {//倒的包是import android.content.DialogInterface.OnClickListener;
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which) {
                                case ACTION_DETAILS:
                                    showDetails(position);//这个position在mGenerals.get(position);调用,说明position是资源总条数范围,
                                    break;
                                case ACTION_ADD:
                                    
                                    break;
                                case ACTION_DELETE:
                                    mAdapter.remove(position);//调用适配器的删除方法
                                    break;
                                case ACTION_UPDATE:
                                    //启动修改的Activity,并将当前的军事家对象传递过去
                                    Intent intent=new Intent(MainActivity.this, UpdateActivity.class);
                                    intent.putExtra("general", mGenerals.get(position));//mGenerals.get(position)的对象要实现序列化接口
                                    mPosition=position;
                                    startActivityForResult(intent, ACTION_UPDATE);//要求返回结果,ACTION_UPDATE是requestCode
                                    break;
                                }
                            }
    
                            private void showDetails(int position) {
                                GeneralBean general=mGenerals.get(position);
                                AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
                                builder.setTitle(general.getName())
                                    .setMessage(general.getDetails())
                                    .setPositiveButton("返回", null);//直接关闭,没有响应事件
                                AlertDialog dialog = builder.create();
                                dialog.show();
                            }
                        });
                        AlertDialog dialog = builder.create();
                        dialog.show();
                    return true;
                }
            });
        }
    
        private void initView() {
            mlvGeneral=(ListView) findViewById(R.id.lvGeneral);
            mAdapter=new GeneralAdapter(mGenerals, this);
            mlvGeneral.setAdapter(mAdapter);
        }
    
        private void initData() {
            String[] names=getResources().getStringArray(R.array.general);
            String[] details=getResources().getStringArray(R.array.details);
            int[] resid={
                    R.drawable.baiqi,R.drawable.caocao,R.drawable.chengjisihan,
                    R.drawable.hanxin,R.drawable.lishimin,R.drawable.nuerhachi,
                    R.drawable.sunbin,R.drawable.sunwu,R.drawable.yuefei,
                    R.drawable.zhuyuanzhang
                };
            mGenerals=new ArrayList<GeneralBean>();
            for (int i = 0; i < resid.length; i++) {
                GeneralBean general=new GeneralBean(resid[i], names[i], details[i]);
                mGenerals.add(general);
            }
        }
    
        class GeneralAdapter extends BaseAdapter{
            List<GeneralBean> generals;
            MainActivity context;
            
            public void remove(int position){//适配器移出方法,就是移除资源总数据,
                generals.remove(position);
                notifyDataSetChanged();//BaseAdapter的方法,执行后安卓系统会调用getView()方法重新绘制,
            }
            
            public void add(GeneralBean general){
                mGenerals.add(general);
                notifyDataSetChanged();
            }
            
            public void update(int position,GeneralBean general){
                mGenerals.set(position, general);
                notifyDataSetChanged();
            }
            
            public GeneralAdapter(List<GeneralBean> generals, MainActivity context) {
                super();
                this.generals = generals;
                this.context = context;
            }
    
            @Override
            public int getCount() {
                return generals.size();
            }
    
            @Override
            public Object getItem(int position) {
                // TODO Auto-generated method stub
                return null;
            }
    
            @Override
            public long getItemId(int position) {
                // TODO Auto-generated method stub
                return 0;
            }
    
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                ViewHolder holder=null;
                if(convertView==null){
                    convertView=View.inflate(context, R.layout.item_general, null);
                    holder=new ViewHolder();
                    holder.ivThumb=(ImageView) convertView.findViewById(R.id.ivThumb);
                    holder.tvName=(TextView) convertView.findViewById(R.id.tvName);
                    convertView.setTag(holder);
                }else{//滚屏的时候重复利用convertView
                    holder=(ViewHolder) convertView.getTag();
                }
                GeneralBean general=generals.get(position);
                holder.ivThumb.setImageResource(general.getResid());
                holder.tvName.setText(general.getName());
                return convertView;
            }
            
            class ViewHolder{
                ImageView ivThumb;
                TextView tvName;
            }
        }
        
        @Override
        //处理UpdateActivity返回的结果
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if(resultCode!=RESULT_OK){//判断resultCode
                return ;
            }
            switch (requestCode) {//判断requestCode
            case ACTION_UPDATE:
                GeneralBean general=(GeneralBean) data.getSerializableExtra("general");//获取修改完以后的对象
                mAdapter.update(mPosition, general);//调用适配器的更新方法,mPosition是修改的对象在集合的索引
                break;
            case ACTION_ADD:
                
                break;
            }
        }
    }

    mainactivity页面:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    
        <ListView
            android:id="@+id/lvGeneral"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    
    </RelativeLayout>

    修改Activity:

    package com.sxt.day05_11;
    
    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.EditText;
    import android.widget.ImageView;
    
    import com.sxt.day05_11.entity.GeneralBean;
    
    public class UpdateActivity extends Activity {
        //要修改对象的名字(控件显示),详细信息(控件显示),
        EditText metName,metDetails;
        ImageView mivThumb;//图片
        int mPhotoId;//图片id
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_update);
            initView();
            initData();
            setListener();
        }
    
        private void setListener() {
            setOKClickListtener();
            setCancelClickListener();
        }
    
        private void setCancelClickListener() {
            findViewById(R.id.btnCancel).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        }
    
        private void setOKClickListtener() {
            findViewById(R.id.btnOK).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    String details=metDetails.getText().toString();
                    String name=metName.getText().toString();
                    //不能根据图片控件获取图片的id,所以多用一个变量保存图片的id
                    GeneralBean general=new GeneralBean(mPhotoId, name, details);
                    Intent intent=new Intent(UpdateActivity.this, MainActivity.class);
                    intent.putExtra("general", general);
                    setResult(RESULT_OK, intent);//RESULT_OK是resultCode结果码
                    finish();//关闭当前页面
                }
            });
        }
    
        //接收数据
        private void initData() {
            Intent intent = getIntent();
            GeneralBean general=(GeneralBean) intent.getSerializableExtra("general");
            //数据显示在控件里面
            metDetails.setText(general.getDetails());
            metName.setText(general.getName());
            mivThumb.setImageResource(general.getResid());//图片是根据id获取的
            mPhotoId=general.getResid();//保存图片id
        }
    
        private void initView() {
            //用布局实例化对象
            metDetails=(EditText) findViewById(R.id.etDetails);
            metName=(EditText) findViewById(R.id.etName);
            mivThumb=(ImageView) findViewById(R.id.iv_updae_thumb);
        }
    
    }

    修改Activity页面:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <ImageView
            android:id="@+id/iv_updae_thumb"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:scaleType="fitXY"                   
            android:src="@drawable/baiqi"/>
        <EditText                                           可编辑的输入框
            android:id="@+id/etName"
            android:layout_below="@id/iv_updae_thumb"
            android:layout_width="80dp"
            android:layout_height="wrap_content"
            android:text="白起"/>
        <EditText 
            android:id="@+id/etDetails"
            android:layout_width="match_parent"
            android:layout_height="110dp"
            android:text="@string/detail"
            android:layout_toRightOf="@id/iv_updae_thumb"/>
        
        <Button 
            android:id="@+id/btnOK"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="修改"
            android:layout_below="@id/etDetails"
            android:layout_marginLeft="50dp"
            android:layout_marginTop="20dp"/>
        <Button 
            android:id="@+id/btnCancel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="放弃"
            android:layout_below="@id/etDetails"
            android:layout_marginTop="20dp"
            android:layout_toRightOf="@id/btnOK"
            android:layout_marginLeft="50dp"/>
        
    </RelativeLayout>

    item_general.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="horizontal" >         横向
        
        <ImageView 
            android:id="@+id/ivThumb"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:scaleType="fitXY"                  自动缩放
            android:src="@drawable/baiqi"/>
    
        <TextView 
            android:id="@+id/tvName"
            android:layout_width="wrap_content"
            android:layout_height="60dp"
            android:gravity="center_vertical"        内部垂直居中
            android:textSize="20sp"
            android:text="白起"
            android:layout_marginLeft="10dp"/>    
    </LinearLayout>
  • 相关阅读:
    eclipse运行maven项目报错:找不到ContextLoaderListener、IntrospectorCleanupListener
    音乐播放器项目计划进度安排
    音乐播放器计划书
    抽奖程序
    显示默认目录中的所有文件名
    单字符和多字符的文件输出
    求和
    第二周 登录小界面
    第一周随笔
    小组图书管理系统项目进度表
  • 原文地址:https://www.cnblogs.com/yaowen/p/4889382.html
Copyright © 2011-2022 走看看