使用自定义适配器将项目动态添加到列表视图中的问题

java android listview adapter

46 观看

1回复

6 作者的声誉

我有问题要添加项目动态到list viewcustom adapter当我点击按钮。实际上,最后一个短信被新短信覆盖。

我给你看我的代码!

预先感谢大家...我希望你能帮助我!

型号类别:

public class Sms {
    String nome;
    String testo;

    public Sms(String nome, String testo ) {

        this.nome=nome;
        this.testo=testo;

    }

    public String getNome() {
        return nome;
    }

    public String getTesto() {
        return testo;
    }


}

定制适配器:

public class CustomAdapter extends ArrayAdapter<Sms> {

    private ArrayList<Sms> dataSms;
    Context mContext;
    //ArrayList<Location> data = new ArrayList<Location>();
    // View lookup cache
    private static class ViewHolder {
        TextView txtNome;
        TextView txtTesto;
    }

    public CustomAdapter(ArrayList<Sms> data, Context context) {
        super(context, R.layout.row_item, data);
        this.dataSms = data;
        this.mContext=context;

    }

/*    @Override
    public void onClick(View v) {

        int position=(Integer) v.getTag();
        Object object= getItem(position);
        DataModel dataModel=(DataModel)object;

        switch (v.getId())
        {
            case R.id.item_info:
                Snackbar.make(v, "Release date " +dataModel.getFeature(), Snackbar.LENGTH_LONG)
                        .setAction("No action", null).show();
                break;
        }
    }*/

    //private int lastPosition = -1;
    @Override
    public int getCount() {
        return dataSms.size();
    }
  /*  @Override
    public Object getItem(int pos) {
        return dataSms.get(pos);
    }*/
    @Override
    public long getItemId(int position) {
        return position;
    }
    @Override
    public void add(Sms sms) {
        dataSms.add(sms);
        notifyDataSetChanged();
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Get the data item for this position
        Sms sms = getItem(position);
        // Check if an existing view is being reused, otherwise inflate the view
        ViewHolder viewHolder; // view lookup cache stored in tag

        final View result;

        if (convertView == null) {

            viewHolder = new ViewHolder();
            LayoutInflater inflater = LayoutInflater.from(getContext());
            convertView = inflater.inflate(R.layout.row_item, parent, false);
            viewHolder.txtNome = (TextView) convertView.findViewById(R.id.nome);
            viewHolder.txtTesto = (TextView) convertView.findViewById(R.id.testo);

            result=convertView;

            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
            result=convertView;
        }

        /*Animation animation = AnimationUtils.loadAnimation(mContext, (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
        result.startAnimation(animation);*/
       // lastPosition = position;

        viewHolder.txtNome.setText(sms.getNome());
        viewHolder.txtTesto.setText(sms.getTesto());
        /*viewHolder.info.setOnClickListener(this);
        viewHolder.info.setTag(position);*/
        // Return the completed view to render on screen
        return convertView;
    }
}

主要活动:

public class MainActivity extends Activity {
    private static final int PERMS_REQUEST_CODE = 123;
    private static final int REQUEST_CODE = 1;
    TextView textViewTime;
    TimePicker timePicker;
    Button button;

    ArrayList<Sms> dataSms;
    ListView listView;
    public static CustomAdapter adapter;

    int hour;
    int minutee;
    //int hour;
    //int minute;
    //ListView lv;
    //ArrayList<String> al;
    //ArrayAdapter<String> aa;

    final int TIME_DIALOG_ID = 999;

    /*public String sPhone,sSms;
    public EditText etPhone,etSms;*/

    public Button bStart, bCancel, bTimeSelect, bPhone;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Button b=(Button) findViewById(R.id.button1);
        //Button button=(Button) findViewById(R.id.button);

        bStart = (Button) findViewById(R.id.bStart);
        //bCancel = (Button)findViewById(R.id.bCancel);
        bTimeSelect = (Button) findViewById(R.id.bTime);
        bPhone = (Button) findViewById(R.id.bCPhone);


        bStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            /*  if (hasPermissions()) {
                    // our app has permissions.
                    scheduleAlarm(v);
                } else {
                    //our app doesn't have permissions, So i m requesting permissions.
                    requestPerms();
                }*/
                scheduleAlarm(v);

            }
        });

        bTimeSelect.setOnClickListener(new View.OnClickListener() {
            @TargetApi(Build.VERSION_CODES.HONEYCOMB)
            @Override
            public void onClick(View v) {

                DialogFragment newFragment = new TimePickerFragment();
                newFragment.show(getFragmentManager(), "TimePicker");

            }
        });

        //};
        bPhone.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Uri uri = Uri.parse("content://contacts");
                Intent intent = new Intent(Intent.ACTION_PICK, uri);
                intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
                startActivityForResult(intent, REQUEST_CODE);
            }
        });


    }


    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @SuppressLint("ValidFragment")
    public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {

        //TimePicker timePicker;
        //int hour;
        //int minutee;

        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            //Use the current time as the default values for the time picker
            final Calendar c = Calendar.getInstance();
            int hour = c.get(Calendar.HOUR_OF_DAY);
            int minute = c.get(Calendar.MINUTE);

            //Create and return a new instance of TimePickerDialog
            return new TimePickerDialog(getActivity(), this, hour, minute,
                    DateFormat.is24HourFormat(getActivity()));
        }


        //onTimeSet() callback method
        @TargetApi(Build.VERSION_CODES.M)
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

            hour = hourOfDay;
            minutee = minute;


        }
    }


    @TargetApi(Build.VERSION_CODES.M)
    public void scheduleAlarm(View V) {


        listView = (ListView) findViewById(R.id.listView1);

        dataSms = new ArrayList<>();


        EditText et1 = (EditText) findViewById(R.id.etPhone);
        EditText et2 = (EditText) findViewById(R.id.etSms);
        String name = et1.getText().toString();
        String sms = et2.getText().toString();


        dataSms.add(new Sms(name, sms));
        adapter = new CustomAdapter(dataSms, getApplicationContext());

        listView.setAdapter(adapter);


        // PendingIntent pendingIntent;
        //Long time= new GregorianCalendar().getTimeInMillis()+24*60*60*1000;
        // Long time = new GregorianCalendar().getTimeInMillis() + 10000;
        //Long time= System.currentTimeMillis() + 10000;

        Intent intentAlarm = new Intent(this, AlarmReceiver.class);
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Bundle bundle = new Bundle();
        bundle.putCharSequence("Number", name);
        bundle.putCharSequence("Message", sms);
        intentAlarm.putExtras(bundle);


        final Calendar c = Calendar.getInstance();
        c.setTimeInMillis(System.currentTimeMillis());
        c.set(Calendar.HOUR_OF_DAY, hour);
        c.set(Calendar.MINUTE, minutee);
        //alarmManager.set(AlarmManager.RTC_WAKEUP, time, PendingIntent.getBroadcast(this, 1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
        alarmManager.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), PendingIntent.getBroadcast(this, 1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));


        Toast.makeText(this, "Messaggio programmato!", Toast.LENGTH_LONG).show();


    }
}
作者: Lo_Zio 的来源 发布者: 2017 年 1 月 19 日

回应 1


1

2056 作者的声誉

决定

将此代码移到onCreate方法

    listView = (ListView) findViewById(R.id.listView1);
    dataSms = new ArrayList<>();
    adapter = new CustomAdapter(dataSms, getApplicationContext());
    listView.setAdapter(adapter);

并在scheduleAlarm方法内部创建并在适配器上添加消息

adapter.add(new Sms(name, sms));
作者: Panayiotis Irakleous 发布者: 2017 年 1 月 19 日
32x32