Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ru.kurganec.vk.messenger.ui.fragments;
- import android.app.Activity;
- import android.content.ContentValues;
- import android.content.Intent;
- import android.database.Cursor;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.net.Uri;
- import android.os.AsyncTask;
- import android.os.Bundle;
- import android.provider.MediaStore;
- import android.support.v4.app.FragmentManager;
- import android.support.v4.app.FragmentTransaction;
- import android.text.Editable;
- import android.util.Log;
- import android.util.SparseBooleanArray;
- import android.view.LayoutInflater;
- import android.view.MotionEvent;
- import android.view.View;
- import android.view.ViewGroup;
- import android.widget.*;
- import ru.kurganec.vk.messenger.R;
- import ru.kurganec.vk.messenger.model.ImageDownloader;
- import ru.kurganec.vk.messenger.model.VK;
- import ru.kurganec.vk.messenger.model.VKDatabase;
- import ru.kurganec.vk.messenger.model.classes.VKMessage;
- import ru.kurganec.vk.messenger.model.classes.VKProfile;
- import ru.kurganec.vk.messenger.ui.CompanionPickerActivity;
- import ru.kurganec.vk.messenger.ui.LocationPickerActivity;
- import ru.kurganec.vk.messenger.ui.SingleDialogActivity;
- import ru.kurganec.vk.messenger.ui.helper.AttachPopUp;
- import ru.kurganec.vk.messenger.ui.helper.BaseVKFragment;
- import ru.kurganec.vk.messenger.ui.helper.VKImageButton;
- import ru.kurganec.vk.messenger.ui.helper.VKImageView;
- import ru.kurganec.vk.messenger.ui.helper.adapters.HistoryAdapter;
- import ru.kurganec.vk.messenger.utils.BaseActionsObserver;
- import ru.kurganec.vk.messenger.utils.EmptyTextWatcher;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- /**
- * User: anatoly
- * Date: 19.06.12
- * Time: 15:19
- */
- public class SingleDialogFragment extends BaseVKFragment implements AttachPopUp.AttachActionListener,
- BaseVKFragment.Updatable {
- private static final int REQUEST_CAMERA_CAPTURE = 1;
- private static final int REQUEST_PICK_FROM_GALLERY = 2;
- private static final int REQUEST_PICK_LOCATION = 3;
- private VKProfile mProfile;
- DialogObserver mObserver = new DialogObserver();
- HistoryAdapter mAdapter;
- ListView mList;
- EditText mInput;
- TextView footerUserIsTyping;
- AttachPopUp mAttachWindow;
- private Uri mImageUri;
- private AttachHandler mAttachHandler;
- FrameLayout navigation;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- Bundle args = getArguments();
- long profileUID = getArguments().getLong(SingleDialogActivity.EXTRA_PROFILE_UID);
- mProfile = VK.db().getProfile(profileUID);
- if (mProfile == null) {
- getActivity().finish();
- return;
- }
- List<VKMessage> hist = VK.db().getProfileHistory(mProfile.getUid(), VKDatabase.FROM_INF);
- mAdapter = new HistoryAdapter(getActivity(), hist);
- }
- @Override
- public void onResume() {
- super.onResume();
- List<VKMessage> hist = VK.db().getProfileHistory(mProfile.getUid(), VKDatabase.FROM_INF);
- if (hist.size() < 15) {
- VK.actions().getProfileHistory(mProfile.getUid(), 20, 0);
- }
- mAdapter.setData(hist);
- VK.actions().registerObserver(mObserver);
- }
- @Override
- public void onPause() {
- VK.actions().unRegisterObserver(mObserver);
- super.onPause();
- }
- @Override
- public void onDestroy() {
- super.onDestroy();
- mObserver = null;
- }
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
- View root = inflater.inflate(R.layout.fragment_single_dialog, container, false);
- TextView v = (TextView) root.findViewById(R.id.text_name);
- v.setText(mProfile.getLastName() + " " + mProfile.getFirstName());
- mList = (ListView) root.findViewById(R.id.list_history);
- mList.setAdapter(mAdapter);
- mList.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_NORMAL);
- mList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
- mList.setItemsCanFocus(false);
- mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
- @Override
- public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
- handleMessageSelection();
- }
- });
- mList.setOnTouchListener(new View.OnTouchListener() {
- @Override
- public boolean onTouch(View view, MotionEvent motionEvent) {
- return false;
- }
- });
- mList.setOnScrollListener(new AbsListView.OnScrollListener() {
- int currentState;
- @Override
- public void onScrollStateChanged(AbsListView absListView, int state) {
- currentState = state;
- }
- @Override
- public void onScroll(AbsListView absListView, int firstVisible, int countVisible, int allCount) {
- if (currentState != SCROLL_STATE_FLING) {
- ArrayList<VKMessage> unread = new ArrayList<VKMessage>();
- for (int position = firstVisible; position < firstVisible + countVisible; ++position) {
- VKMessage msg = (VKMessage) mAdapter.getItem(position);
- if (msg.getReadState() == VKMessage.UNREAD && msg.getOutState() == VKMessage.IN) {
- unread.add(msg);
- }
- }
- if (unread.size() > 0) {
- VK.actions().markAsRead(unread);
- }
- }
- }
- });
- footerUserIsTyping = (TextView) root.findViewById(R.id.text_user_typing);
- Button backButton = (Button) root.findViewById(R.id.btn_back);
- backButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- getActivity().finish();
- }
- });
- mInput = (EditText) root.findViewById(R.id.input_msg);
- mInput.addTextChangedListener(new EmptyTextWatcher() {
- @Override
- public void afterTextChanged(Editable editable) {
- if (editable.length() % 7 == 0 || editable.length() == 1) {
- VK.actions().iAmTyping(mProfile.getUid());
- }
- }
- });
- Button btn = (Button) root.findViewById(R.id.btn_send);
- btn.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- VK.actions().sendMessage(mProfile.getUid(),
- mInput.getText().toString(),
- mAttachHandler.getFileNames(),
- mAttachHandler.getForward(),
- mAttachHandler.getLatitude(),
- mAttachHandler.getLongitude()
- );
- mInput.setText("");
- mAttachHandler.clear();
- }
- });
- VKImageView avatar = (VKImageView) root.findViewById(R.id.ic_avatar);
- avatar.setURI(mProfile.getPhoto());
- mAttachWindow = AttachPopUp.build(getActivity());
- mAttachWindow.setAttachListener(SingleDialogFragment.this);
- final Button btnAttach = (Button) root.findViewById(R.id.btn_attach);
- btnAttach.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- if (mAttachHandler.shown()) {
- mAttachHandler.hide();
- } else {
- if (mAttachHandler.empty()) {
- if (!mAttachWindow.isShowing()) {
- mAttachWindow.show();
- }
- } else {
- mAttachHandler.show();
- }
- }
- }
- });
- FrameLayout wrapper = (FrameLayout) root.findViewById(R.id.attach_wrapper);
- mAttachHandler = new AttachHandler(wrapper);
- if (getArguments().containsKey(CompanionPickerActivity.EXTRA_MIDS_TO_FORWARD)){
- mAttachHandler.handleForward(getArguments().getString(CompanionPickerActivity.EXTRA_MIDS_TO_FORWARD));
- }
- return root;
- }
- private MessagesActionFragment mMessageActions = new MessagesActionFragment();
- private int previousCount = 0;
- private void handleMessageSelection() {
- SparseBooleanArray arr = mList.getCheckedItemPositions();
- int count = 0;
- List<VKMessage> selected = new ArrayList<VKMessage>();
- for (int i = 0; i < arr.size(); ++i) {
- int key = arr.keyAt(i);
- if (arr.get(key)) {
- selected.add((VKMessage) mAdapter.getItem(key));
- count++;
- }
- }
- if (count == 1 && previousCount == 0) {
- FragmentManager manager = getFragmentManager();
- FragmentTransaction t = manager.beginTransaction();
- t.replace(R.id.navigation, mMessageActions);
- mMessageActions.pass(selected, this);
- t.addToBackStack("selected item");
- t.commit();
- } else if (count == 0) {
- getFragmentManager().popBackStackImmediate();
- } else {
- mMessageActions.pass(selected, this);
- }
- previousCount = count;
- }
- @Override
- public void onAction(AttachPopUp.Action a) {
- switch (a) {
- case ACTION_GALLERY: {
- requestGallery();
- break;
- }
- case ACTION_PHOTO: {
- requestPhoto();
- break;
- }
- case ACTION_GEO: {
- requestGeo();
- break;
- }
- }
- }
- @Override
- public void onActivityResult(int requestCode, int resultCode, Intent data) {
- if (mAttachWindow.isShowing()) {
- mAttachWindow.dismiss();
- }
- if (resultCode == Activity.RESULT_OK) {
- mAttachHandler.show();
- switch (requestCode) {
- case REQUEST_PICK_FROM_GALLERY: {
- Uri selectedImage = data.getData();
- String[] filePathColumn = {MediaStore.Images.Media.DATA};
- Cursor cursor = getActivity().getContentResolver().
- query(selectedImage, filePathColumn, null, null, null);
- cursor.moveToFirst();
- int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
- String filePath = cursor.getString(columnIndex);
- cursor.close();
- //filePath
- mAttachHandler.handlePhoto(filePath);
- break;
- }
- case REQUEST_CAMERA_CAPTURE: {
- Uri selectedImage = mImageUri;
- String[] filePathColumn = {MediaStore.Images.Media.DATA};
- Cursor cursor = getActivity().getContentResolver().
- query(selectedImage, filePathColumn, null, null, null);
- cursor.moveToFirst();
- int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
- String filePath = cursor.getString(columnIndex);
- cursor.close();
- //filePath
- mAttachHandler.handlePhoto(filePath);
- break;
- }
- case REQUEST_PICK_LOCATION: {
- int lat = data.getIntExtra("latitude", 0);
- int lon = data.getIntExtra("longitude", 0);
- mAttachHandler.handleGeo(lat, lon);
- break;
- }
- }
- }
- }
- private void requestGallery() {
- Intent takePictureFromGalleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
- startActivityForResult(takePictureFromGalleryIntent, REQUEST_PICK_FROM_GALLERY);
- }
- private void requestPhoto() {
- ContentValues values = new ContentValues();
- mImageUri = getActivity().
- getContentResolver().
- insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
- Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
- takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
- startActivityForResult(takePictureIntent, REQUEST_CAMERA_CAPTURE);
- }
- private void requestGeo() {
- Intent i = new Intent(getActivity(), LocationPickerActivity.class);
- startActivityForResult(i, REQUEST_PICK_LOCATION);
- }
- @Override
- public void update() {
- List<VKMessage> hist = VK.db().
- getProfileHistory(mProfile.getUid(),
- mAdapter.getCount() > 0 ? ((VKMessage) mAdapter.getItem(0)).getMid() : VKDatabase.FROM_INF);
- mAdapter.setData(hist);
- mList.clearChoices();//TODO does not work!!!
- previousCount = 0;
- }
- private class DialogObserver extends BaseActionsObserver {
- @Override
- public void historyUpdated(long profileUID) {
- if (profileUID == mProfile.getUid()) {
- List<VKMessage> hist = VK.db().getProfileHistory(profileUID, VKDatabase.FROM_INF);
- mAdapter.setData(hist);
- }
- }
- @Override
- public void messageChanged(long uid) {
- if (uid == mProfile.getUid()) {
- List<VKMessage> hist = VK.db().
- getProfileHistory(mProfile.getUid(),
- mAdapter.getCount() > 0 ? ((VKMessage) mAdapter.getItem(0)).getMid() : VKDatabase.FROM_INF);
- mAdapter.setData(hist);
- }
- }
- private AsyncTask<Void, Void, Void> mStatusUpdater;
- @Override
- public void userIsTyping(long uid) {
- if (uid == mProfile.getUid()) {
- if (mStatusUpdater != null) {
- mStatusUpdater.cancel(true);
- }
- mStatusUpdater = new AsyncTask<Void, Void, Void>() {
- @Override
- protected void onPreExecute() {
- footerUserIsTyping.setText(R.string.user_is_typing);
- }
- @Override
- protected Void doInBackground(Void... voids) {
- try {
- Thread.sleep(5 * 1000);
- } catch (InterruptedException e) {
- Log.d("VKLOL", mProfile + "is typing again");
- }
- return null;
- }
- @Override
- protected void onPostExecute(Void aVoid) {
- footerUserIsTyping.setText("");
- }
- };
- mStatusUpdater.execute();
- }
- }
- }
- private class AttachHandler implements View.OnClickListener {
- public static final int MAX_SIZE = 10;
- private FrameLayout wrapper;
- LinearLayout horizontalListView;
- LayoutInflater inflater;
- ArrayList<String> fileNames = new ArrayList<String>();
- String forward ;
- Integer latitude;
- Integer longitude;
- private FrameLayout attachPhoto;
- private FrameLayout attachGallery;
- private FrameLayout attachGeo;
- ImageButton btnGallery;
- ImageButton btnPhoto;
- ImageButton btnGeo;
- private boolean geoButtonAttached = true;
- private boolean galleryButtonAttached = true;
- private boolean photoButtonAttached = true;
- public AttachHandler(FrameLayout wrapper) {
- this.wrapper = wrapper;
- inflater = LayoutInflater.from(getActivity());
- horizontalListView = (LinearLayout) wrapper.findViewById(R.id.list_attach);
- attachGallery = (FrameLayout) inflater.inflate(R.layout.view_btn_attach, null);
- attachPhoto = (FrameLayout) inflater.inflate(R.layout.view_btn_attach, null);
- attachGeo = (FrameLayout) inflater.inflate(R.layout.view_btn_attach, null);
- btnGallery = (ImageButton) attachGallery.findViewById(R.id.btn_do_attach);
- btnPhoto = (ImageButton) attachPhoto.findViewById(R.id.btn_do_attach);
- btnGeo = (ImageButton) attachGeo.findViewById(R.id.btn_do_attach);
- btnGallery.setBackgroundResource(R.drawable.bg_btn_gallery);
- btnPhoto.setBackgroundResource(R.drawable.bg_btn_photo);
- btnGeo.setBackgroundResource(R.drawable.bg_btn_geo);
- btnGallery.setOnClickListener(this);
- btnPhoto.setOnClickListener(this);
- btnGeo.setOnClickListener(this);
- clear();
- }
- public boolean shown() {
- return wrapper.getVisibility() == View.VISIBLE;
- }
- private HashMap<String, View> attaches = new HashMap<String, View>();
- void handlePhoto(final String fileName) {
- if (fileNames.contains(fileName)) {
- return;
- }
- fileNames.add(fileName);
- BitmapFactory.Options options = new BitmapFactory.Options();
- options.inSampleSize = 3;
- Bitmap b = BitmapFactory.decodeFile(fileName, options);
- View newAttach = inflater.inflate(R.layout.view_attached, null);
- ImageButton btn = (ImageButton) newAttach.findViewById(R.id.btn_attached);
- btn.setImageBitmap(b);
- ImageButton btnDelete = (ImageButton) newAttach.findViewById(R.id.btn_delete_attach);
- btnDelete.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- removePhoto(fileName);
- }
- });
- horizontalListView.addView(newAttach, 0);
- attaches.put(fileName, newAttach);
- handleMaxSize();
- }
- private void handleMaxSize() {
- if (size() >= MAX_SIZE) {
- if (geoButtonAttached) {
- horizontalListView.removeView(attachGeo);
- geoButtonAttached = false;
- }
- if (galleryButtonAttached) {
- horizontalListView.removeView(attachGallery);
- galleryButtonAttached = false;
- }
- if (photoButtonAttached) {
- horizontalListView.removeView(attachPhoto);
- photoButtonAttached = false;
- }
- } else {
- if (!photoButtonAttached) {
- int count = horizontalListView.getChildCount();
- horizontalListView.addView(attachPhoto, count);
- photoButtonAttached = true;
- }
- if (!galleryButtonAttached) {
- int count = horizontalListView.getChildCount();
- horizontalListView.addView(attachGallery, count);
- galleryButtonAttached = true;
- }
- if (!geoButtonAttached && latitude == null) {
- int count = horizontalListView.getChildCount();
- horizontalListView.addView(attachGeo, count);
- geoButtonAttached = true;
- }
- }
- }
- private void removePhoto(String fileName) {
- if (fileNames.remove(fileName)) {
- View v = attaches.get(fileName);
- horizontalListView.removeView(v);
- } else {
- Log.e("VKLOL", "FTW removed photo doesnot exist");
- }
- handleMaxSize();
- }
- public void clear() {
- hide();
- horizontalListView.removeAllViews();
- fileNames.clear();
- forward = null;
- latitude = null;
- longitude = null;
- horizontalListView.addView(attachPhoto);
- horizontalListView.addView(attachGallery);
- horizontalListView.addView(attachGeo);
- }
- public void handleGeo(int lat, int lon) {
- latitude = lat;
- longitude = lon;
- View newAttach = inflater.inflate(R.layout.view_attached, null);
- VKImageButton btn = (VKImageButton) newAttach.findViewById(R.id.btn_attached);
- btn.setImageResource(R.drawable.ic_attach_geo);
- btn.setURI(ImageDownloader.getMapPreviewUri(lat, lon, true));
- horizontalListView.addView(newAttach, 0);
- ImageButton btnDelete = (ImageButton) newAttach.findViewById(R.id.btn_delete_attach);
- btnDelete.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- removeGeo();
- }
- });
- attaches.put("geo", newAttach);
- horizontalListView.removeView(attachGeo);
- geoButtonAttached = false;
- handleMaxSize();
- }
- public void handleForward(String fwd){
- forward = fwd;//TODO ADd here forward icon
- handleMaxSize();
- }
- private void removeGeo() {
- latitude = null;
- longitude = null;
- View v = attaches.get("geo");
- horizontalListView.removeView(v);
- int count = horizontalListView.getChildCount();
- horizontalListView.addView(attachGeo, count);
- geoButtonAttached = true;
- handleMaxSize();
- }
- public int size() {
- int count = 0;
- count += fileNames.size();
- count += forward!= null ? 1 : 0;
- if (latitude != null) {
- count += 1;
- }
- return count;
- }
- public void show() {
- wrapper.setVisibility(View.VISIBLE);
- }
- public void hide() {
- wrapper.setVisibility(View.GONE);
- }
- public boolean empty() {
- return fileNames.size() == 0 && forward != null && latitude == null && longitude == null;
- }
- public Integer getLongitude() {
- return longitude;
- }
- public Integer getLatitude() {
- return latitude;
- }
- public String getForward() {
- return forward;
- }
- public ArrayList<String> getFileNames() {
- return fileNames;
- }
- @Override
- public void onClick(View view) {
- if (view == btnGeo) {
- requestGeo();
- } else if (view == btnPhoto) {
- requestPhoto();
- } else {
- requestGallery();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment