如何限制arrayadapter中listview的项目,并使用LoadPrevious标头加载更多项目

时间:2017-11-01 12:17:01

标签: android listview

我的活动

public class UserComments extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_comments);

        lv= (ListView) findViewById(R.id.Listview_common);

        realm=Realm.getDefaultInstance();
        Button btnLoadMore = new Button(this);
        btnLoadMore.setText("Load Previous");
        lv.addHeaderView(btnLoadMore);
        btnLoadMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                realm = Realm.getDefaultInstance();
                int position;
                position = lv.getCheckedItemPosition();
                position = position - 1;
                lv.getItemAtPosition(position);
                int last = lv.getLastVisiblePosition();
                if (position == 1) {
                    System.out.println("previous is Impossilble");
                    setAdapter();
                }
            }
        });
        displayInputDialog();
        imgattach=(ImageView) findViewById(R.id.imgattach);
        imgattach.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                selectImage();
            }
        });
    }

    public void setAdapter()
    {
        lv= (ListView) findViewById(R.id.Listview_common);
        final UserCommentRealmHelper helper=new UserCommentRealmHelper(realm);
        helper.retrieveFromDB();
        UserCommentArrayAdapter adapter=new UserCommentArrayAdapter(UserComments.this,helper.justRefresh());
        lv.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        realmChangeListener=new RealmChangeListener() {
            @Override
            public void onChange() {
                UserCommentArrayAdapter adapter=new UserCommentArrayAdapter(UserComments.this,helper.justRefresh());
                lv.setAdapter(adapter);
                adapter.notifyDataSetChanged();
            }
        };
        realm.addChangeListener(realmChangeListener);
    }
    public void displayInputDialog()
    {
        descEditTxt= (EditText) findViewById(R.id.editwrite);
        ImageView fab = (ImageView) findViewById(R.id.send);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String desc = descEditTxt.getText().toString();
                UserComment s = new UserComment();
                s.setDescription(desc);
                UserCommentRealmHelper helper = new UserCommentRealmHelper(realm);
                if (helper.save(s)) {
                    descEditTxt.setText("");
                    setAdapter();
                }
                else {
                    Toast.makeText(UserComments.this, "Invalid Data", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    public void cameraIntent() {
        Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, REQUEST_CAMERA);
        intent.putExtra("camera",REQUEST_CAMERA);

    }
    public void galleryIntent() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);//
        startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
    }
    public void selectImage() {
        final CharSequence[] items = { "Take Photo", "Choose from Library","Camera Video","Gallery Video",
                "Cancel" };
        AlertDialog.Builder builder = new AlertDialog.Builder(UserComments.this);
        builder.setTitle("Add Photo!");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                boolean result=Utility.checkPermission(UserComments.this);
                if (items[item].equals("Take Photo")) {
                    userChoosenTask="Take Photo";
                    if(result)
                        cameraIntent();
                } else if (items[item].equals("Choose from Library")) {
                    userChoosenTask="Choose from Library";
                    if(result)
                        galleryIntent();
                }
                else if (items[item].equals("Camera Video")) {
                    userChoosenTask="Camera Video";
                    if(result)
                        startRecording();
                }
                else if (items[item].equals("Gallery Video")) {
                    userChoosenTask="Gallery Video";
                    if(result)
                        CaptureVideoFromGallery();

                }
                else if (items[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }
    public void CaptureVideoFromGallery()
    {
        Intent intent = new Intent();
        intent.setType("video/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Video"), SELECT_FILES);
    }
    public void startRecording()
    {

        java.util.Date date= new java.util.Date();
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(date.getTime());

        File mediaFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/"+timeStamp+".mp4");
        ///   File mediaFile = new File(Environment.getExternalStorageDirectory(),System.currentTimeMillis() + ".mp4");
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        fileUri = Uri.fromFile(mediaFile);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        startActivityForResult(intent, VIDEO_CAPTURE);
    }
    /** Create a file Uri for saving an image or video */
    private static Uri getOutputMediaFileUri(int type){

        return Uri.fromFile(getOutputMediaFile(type));
    }

    /** Create a File for saving an image or video */
    private static File getOutputMediaFile(int type){

        // Check that the <a href="#">SDCard</a> is mounted
        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES), "MyCameraVideo");

        if (! mediaStorageDir.exists()){

            if (! mediaStorageDir.mkdirs()){

                Log.d("MyCameraVideo", "Failed to create directory MyCameraVideo.");
                return null;
            }
        }


        // Create a media file name

        // For unique file name appending current timeStamp with file name
        java.util.Date date= new java.util.Date();
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                .format(date.getTime());

        File mediaFile;

        if(type == MEDIA_TYPE_VIDEO) {

            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                    "VID_"+ timeStamp + ".mp4");

        } else {
            return null;
        }

        return mediaFile;
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if(userChoosenTask.equals("Take Photo"))
                        cameraIntent();
                    else if(userChoosenTask.equals("Choose from Library"))
                        galleryIntent();
                    else if(userChoosenTask.equals("Video"))
                        startRecording();
                } else {
                }
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == SELECT_FILE) {
                onSelectFromGalleryResult(data);
            }
            else if (requestCode == REQUEST_CAMERA) {
                onCaptureImageResult(data);
            }
            else if (requestCode == SELECT_FILES) {
                onSelectFromGalleryVideoResults(data);
            }
            else if (requestCode == VIDEO_CAPTURE) {
                Toast.makeText(this, "Video has been saved to:\n" + data.getData(), Toast.LENGTH_LONG).show();
                SaveVideoData(String.valueOf(data.getData()));
            } else if (resultCode == RESULT_CANCELED) {
                Toast.makeText(this, "Video recording cancelled.", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "Failed to record video", Toast.LENGTH_LONG).show();
            }



        }
    }
    public void SaveVideoData(String data) {
        try {
            Realm realm = Realm.getDefaultInstance();
            realm.beginTransaction();
            UserComment s = realm.createObject(UserComment.class);
            s.setVideoUrl(data);
            realm.commitTransaction();
            realm.close();
            UserCommentRealmHelper helper = new UserCommentRealmHelper(realm);
            if (helper.save(s)) {
                setAdapter();
            }
            else
            {
                Toast.makeText(UserComments.this, "Invalid Data", Toast.LENGTH_SHORT).show();
            }
            Log.d("path", data);
            Log.d("working realm", "yes....");
            Toast.makeText(getApplicationContext(),"Set Image URL"+data,Toast.LENGTH_LONG).show();
        }
        catch (Exception ex){
            Toast.makeText(getApplicationContext(),"Nope its not done",Toast.LENGTH_LONG).show();
        }
    }
    public String getRealPathFromURI(Uri contentUri) {
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
    @SuppressWarnings("deprecation")
    public void onSelectFromGalleryResult(Intent data) {
       // Toast.makeText(UserComments.this,"My bm"+data,Toast.LENGTH_LONG).show();
        SaveImageVideoData(String.valueOf(data.getData()),true);

    }
    @SuppressWarnings("deprecation")
    public void onSelectFromGalleryVideoResults(Intent data) {

        Toast.makeText(UserComments.this,"My bm"+data,Toast.LENGTH_LONG).show();
        SaveVideoData(String.valueOf(data));

    }
    public void  onCaptureImageResult(Intent data) {
        Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        thumbnail.compress(Bitmap.CompressFormat.PNG, 90, bytes);
        File destination = new File(Environment.getExternalStorageDirectory(),
                System.currentTimeMillis() + ".png");
        FileOutputStream fo;
        try {
            destination.createNewFile();
            fo = new FileOutputStream(destination);
            fo.write(bytes.toByteArray());
            fo.close();
            //Toast.makeText(UserComments.this,"No Error",Toast.LENGTH_LONG).show();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            //Toast.makeText(UserComments.this,"Error Arrived",Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            e.printStackTrace();
            //Toast.makeText(UserComments.this,"Error Arrived again",Toast.LENGTH_LONG).show();
        }
        SaveImageVideoData(String.valueOf(destination),false);
        //Toast.makeText(UserComments.this,"its done",Toast.LENGTH_LONG).show();
    }
    public void SaveImageVideoData(String data,boolean flag) {
        try {
            Realm realm = Realm.getDefaultInstance();
            realm.beginTransaction();
            UserComment s = realm.createObject(UserComment.class);
            s.setImageUrl(data);
            s.setFlag(flag);
            realm.commitTransaction();
            realm.close();
            UserCommentRealmHelper helper = new UserCommentRealmHelper(realm);
            if (helper.save(s)) {
                setAdapter();
            }
            else
            {
                Toast.makeText(UserComments.this, "Invalid Data", Toast.LENGTH_SHORT).show();
            }
            Log.d("path", data);
            Log.d("working realm", "yes....");
            Toast.makeText(getApplicationContext(),"Set Image URL"+data,Toast.LENGTH_LONG).show();
        }
        catch (Exception ex){
            Toast.makeText(getApplicationContext(),"Nope its not done",Toast.LENGTH_LONG).show();
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        realm.removeChangeListener(realmChangeListener);
        realm.close();}
}

我的适配器类

public class UserCommentArrayAdapter extends ArrayAdapter<UserComment> {

    public UserCommentArrayAdapter(Context context, List<UserComment> objects){
        super(context,0,objects);
        this.context = context;
        this.mInflater = LayoutInflater.from(context);
        contactList = objects;
    }
    @Override
    public UserComment getItem(int position) {
        return contactList.get(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final UserCommentArrayAdapter.ViewHolder vh;
        if (convertView == null) {
            View view = mInflater.inflate(R.layout.item_commonchat, parent, false);
            vh = UserCommentArrayAdapter.ViewHolder.create((LinearLayout) view);
            view.setTag(vh);
        } else {
            vh = (UserCommentArrayAdapter.ViewHolder) convertView.getTag();
        }
        UserComment s = getItem(position);

        if(s.getVideoUrl()!=null && s.getVideoUrl().length()>0)
        {

            Log.d("start error testing", "videooooooo");

            vh.videoView.setVideoPath(s.getVideoUrl());
            vh.videoView.setMediaController(new MediaController(context));
            vh.videoView.start();

        }
        if(vh.txtbeencnt!=null) {
            vh.txtbeencnt.setVisibility(View.VISIBLE);
            vh.imageView.setVisibility(View.GONE);
            vh.videoView.setVisibility(View.GONE);
            vh.txtbeencnt.setText(s.getDescription());
        }
        if(s.getImageUrl() != null && s.getImageUrl().length()>0) {
            boolean flag= s.isFlag();
            if (flag == true) {
                vh.imageView.setVisibility(View.VISIBLE);
                vh.txtbeencnt.setVisibility(View.GONE);
                vh.videoView.setVisibility(View.GONE);
                Picasso.with(context).load(s.getImageUrl()).placeholder(R.mipmap.ic_launcher).into(vh.imageView);
                Toast.makeText(context, "Got Gallery Image URL" + s.getImageUrl(), Toast.LENGTH_LONG).show();
            } else if (flag == false) {

                vh.imageView.setVisibility(View.VISIBLE);
                vh.txtbeencnt.setVisibility(View.GONE);
                vh.videoView.setVisibility(View.GONE);
                Bitmap bitmap = BitmapFactory.decodeFile(s.getImageUrl());
                vh.imageView.setImageBitmap(bitmap);
                Toast.makeText(context, "Got Camera Image URL" + s.getImageUrl(), Toast.LENGTH_LONG).show();
            }

        }


        return vh.rootView;
    }

    private static class ViewHolder {
        public final LinearLayout rootView;
        public final ImageView imageView;
        public final TextView txtbeencnt;
        public final VideoView videoView;


        private ViewHolder(LinearLayout rootView,TextView txtbeencnt,ImageView imageView,VideoView videoView) {
            this.rootView = rootView;
            this.imageView = imageView;
            this.txtbeencnt = txtbeencnt;
            this.videoView=videoView;

        }

        public static UserCommentArrayAdapter.ViewHolder create(LinearLayout rootView) {
            ImageView  imageView = (ImageView) rootView.findViewById(R.id.img);
            VideoView  videoView = (VideoView) rootView.findViewById(R.id.videoView1);
            TextView txtbeencnt = (TextView) rootView.findViewById(R.id.textdesc);
            return new UserCommentArrayAdapter.ViewHolder(rootView,txtbeencnt,imageView,videoView);
        }

    }
}

想要这样的输出

enter image description here

我搜索了很多但是到处都发现使用getcount()方法返回一些特定的item值,但是这里我没有使用自定义适配器,所以在这种情况下该怎么做?

0 个答案:

没有答案