Example usage for android.view KeyEvent getAction

List of usage examples for android.view KeyEvent getAction

Introduction

In this page you can find the example usage for android.view KeyEvent getAction.

Prototype

public final int getAction() 

Source Link

Document

Retrieve the action of this key event.

Usage

From source file:com.aujur.ebookreader.activity.ReadingFragment.java

@TargetApi(Build.VERSION_CODES.FROYO)
private boolean handleVolumeButtonEvent(KeyEvent event) {

    // Disable volume button handling during TTS
    if (!config.isVolumeKeyNavEnabled() || ttsIsRunning()) {
        return false;
    }// w w w  . jav a2 s  .c  o m

    Activity activity = getActivity();

    if (activity == null) {
        return false;
    }

    boolean invert = false;

    int rotation = Surface.ROTATION_0;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
        Display display = activity.getWindowManager().getDefaultDisplay();
        rotation = display.getRotation();
    }

    switch (rotation) {
    case Surface.ROTATION_0:
    case Surface.ROTATION_90:
        invert = false;
        break;
    case Surface.ROTATION_180:
    case Surface.ROTATION_270:
        invert = true;
        break;
    }

    if (event.getAction() != KeyEvent.ACTION_DOWN) {
        return true;
    }

    if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP) {
        if (invert) {
            pageDown(Orientation.HORIZONTAL);
        } else {
            pageUp(Orientation.HORIZONTAL);
        }
    } else if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN) {
        if (invert) {
            pageUp(Orientation.HORIZONTAL);
        } else {
            pageDown(Orientation.HORIZONTAL);
        }
    }

    return true;
}

From source file:org.mozilla.gecko.BrowserApp.java

@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
    if (AndroidGamepadManager.handleKeyEvent(event)) {
        return true;
    }/*w w  w.j  a v a2 s .c  om*/

    // Global onKey handler. This is called if the focused UI doesn't
    // handle the key event, and before Gecko swallows the events.
    if (event.getAction() != KeyEvent.ACTION_DOWN) {
        return false;
    }

    if ((event.getSource() & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD) {
        switch (keyCode) {
        case KeyEvent.KEYCODE_BUTTON_Y:
            // Toggle/focus the address bar on gamepad-y button.
            if (mBrowserChrome.getVisibility() == View.VISIBLE) {
                if (mDynamicToolbar.isEnabled() && !isHomePagerVisible()) {
                    mDynamicToolbar.setVisible(false, VisibilityTransition.ANIMATE);
                    if (mLayerView != null) {
                        mLayerView.requestFocus();
                    }
                } else {
                    // Just focus the address bar when about:home is visible
                    // or when the dynamic toolbar isn't enabled.
                    mBrowserToolbar.requestFocusFromTouch();
                }
            } else {
                mDynamicToolbar.setVisible(true, VisibilityTransition.ANIMATE);
                mBrowserToolbar.requestFocusFromTouch();
            }
            return true;
        case KeyEvent.KEYCODE_BUTTON_L1:
            // Go back on L1
            Tabs.getInstance().getSelectedTab().doBack();
            return true;
        case KeyEvent.KEYCODE_BUTTON_R1:
            // Go forward on R1
            Tabs.getInstance().getSelectedTab().doForward();
            return true;
        }
    }

    // Check if this was a shortcut. Meta keys exists only on 11+.
    final Tab tab = Tabs.getInstance().getSelectedTab();
    if (Versions.feature11Plus && tab != null && event.isCtrlPressed()) {
        switch (keyCode) {
        case KeyEvent.KEYCODE_LEFT_BRACKET:
            tab.doBack();
            return true;

        case KeyEvent.KEYCODE_RIGHT_BRACKET:
            tab.doForward();
            return true;

        case KeyEvent.KEYCODE_R:
            tab.doReload();
            return true;

        case KeyEvent.KEYCODE_PERIOD:
            tab.doStop();
            return true;

        case KeyEvent.KEYCODE_T:
            addTab();
            return true;

        case KeyEvent.KEYCODE_W:
            Tabs.getInstance().closeTab(tab);
            return true;

        case KeyEvent.KEYCODE_F:
            mFindInPageBar.show();
            return true;
        }
    }

    return false;
}

From source file:org.brandroid.openmanager.activities.OpenExplorer.java

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    if (DEBUG)/* w  w w .  j  a  v  a2  s .  c om*/
        Logger.LogDebug("OpenExplorer.onKeyUp(" + keyCode + "," + event + ")");
    if (event.getAction() != KeyEvent.ACTION_UP)
        return super.onKeyUp(keyCode, event);
    if (MenuUtils.getMenuShortcut(event) != null) {
        if (getCurrentFocus() != null) {
            View cf = getCurrentFocus();
            if (cf instanceof TextView)
                return false;
        }
        MenuItem item = MenuUtils.getMenuShortcut(event);
        if (item != null)
            if (onOptionsItemSelected(item)) {
                showToast(item.getTitle(), Toast.LENGTH_SHORT);
                return true;
            }
    }
    if (keyCode == KeyEvent.KEYCODE_MENU && USE_PRETTY_MENUS) {
        View more = findViewById(R.id.menu_more);
        if (more != null && more.isShown() && more.isClickable() && more.performClick()) {
            Logger.LogDebug("!SHOULD BE HERE!");
            return true;
        } else {
            Logger.LogWarning("Couldn't find \"More Menu\"!");
            MenuBuilder menu = new MenuBuilder(this);
            getSelectedFragment().onCreateOptionsMenu(menu, getMenuInflater());
            getMenuInflater().inflate(R.menu.global, menu);
            onPrepareOptionsMenu(menu);
            showMenu(menu, getCurrentFocus(), true);
        }
    } else if (keyCode == KeyEvent.KEYCODE_BOOKMARK) {
        OpenPath path = getDirContentFragment(false).getPath();
        if (mBookmarks.hasBookmark(path))
            addBookmark(path);
        else
            removeBookmark(path);
    } else if (keyCode >= KeyEvent.KEYCODE_1 && keyCode <= KeyEvent.KEYCODE_9) {
        int pos = keyCode - KeyEvent.KEYCODE_1;
        if (mToolbarButtons != null) {
            if (pos < mToolbarButtons.getChildCount() && mToolbarButtons.getChildAt(pos).performClick())
                return true;
            return false;
        }
        if (mOptsMenu != null && pos < mOptsMenu.size())
            return onOptionsItemSelected(mOptsMenu.getItem(pos));
        if (mMainMenu != null && pos < mMainMenu.size())
            return onOptionsItemSelected(mMainMenu.getItem(pos));
    }
    /*
    if (keyCode == KeyEvent.KEYCODE_BACK) {
       if (mBackQuit) {
    return super.onKeyUp(keyCode, event);
       } else {
    Toast.makeText(this, "Press back again to quit", Toast.LENGTH_SHORT).show();
    mBackQuit = true;
    return true;
       }      
    }*/
    return super.onKeyUp(keyCode, event);
}

From source file:org.brandroid.openmanager.activities.OpenExplorer.java

@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
    if (v == null)
        return false;
    if (DEBUG)//w w  w  .  j a  v  a2s  . c om
        Logger.LogDebug("OpenExplorer.onKey(" + v + "," + keyCode + "," + event + ")");
    if (event.getAction() != KeyEvent.ACTION_UP)
        return false;
    if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER) {
        if (MenuUtils.getMenuLookupID(v.getId()) > 0)
            if (showMenu(MenuUtils.getMenuLookupSub(v.getId()), v, false))
                return true;
    }
    return false;
}

From source file:edu.mit.viral.shen.DroidFish.java

private final Dialog selectPgnSaveNewFileDialog() {
    View content = View.inflate(this, R.layout.create_pgn_file, null);
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setView(content);//from w  w  w . j  a  va  2  s  .c om
    builder.setTitle(R.string.select_pgn_file_save);
    final EditText fileNameView = (EditText) content.findViewById(R.id.create_pgn_filename);
    fileNameView.setText("");
    final Runnable savePGN = new Runnable() {
        public void run() {
            String pgnFile = fileNameView.getText().toString();
            if ((pgnFile.length() > 0) && !pgnFile.contains("."))
                pgnFile += ".pgn";
            String sep = File.separator;
            String pathName = Environment.getExternalStorageDirectory() + sep + pgnDir + sep + pgnFile;
            savePGNToFile(pathName, false);
        }
    };
    builder.setPositiveButton(android.R.string.ok, new Dialog.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            savePGN.run();
        }
    });
    builder.setNegativeButton(R.string.cancel, null);

    final Dialog dialog = builder.create();
    fileNameView.setOnKeyListener(new OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                savePGN.run();
                dialog.cancel();
                return true;
            }
            return false;
        }
    });
    return dialog;
}

From source file:edu.mit.viral.shen.DroidFish.java

private final Dialog selectMoveDialog() {
    View content = View.inflate(this, R.layout.select_move_number, null);
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setView(content);/*from w  ww.j  a  v a  2s.c o m*/
    builder.setTitle(R.string.goto_move);
    final EditText moveNrView = (EditText) content.findViewById(R.id.selmove_number);
    moveNrView.setText("1");
    final Runnable gotoMove = new Runnable() {
        public void run() {
            try {
                int moveNr = Integer.parseInt(moveNrView.getText().toString());
                ctrl.gotoMove(moveNr);
            } catch (NumberFormatException nfe) {
                Toast.makeText(getApplicationContext(), R.string.invalid_number_format, Toast.LENGTH_SHORT)
                        .show();
            }
        }
    };
    builder.setPositiveButton(android.R.string.ok, new Dialog.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            gotoMove.run();
        }
    });
    builder.setNegativeButton(R.string.cancel, null);

    final AlertDialog dialog = builder.create();

    moveNrView.setOnKeyListener(new OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                gotoMove.run();
                dialog.cancel();
                return true;
            }
            return false;
        }
    });
    return dialog;
}

From source file:edu.mit.viral.shen.DroidFish.java

private final Dialog newNetworkEngineDialog() {
    View content = View.inflate(this, R.layout.create_network_engine, null);
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setView(content);/*www.  ja  v  a2  s .c o  m*/
    builder.setTitle(R.string.create_network_engine);
    final EditText engineNameView = (EditText) content.findViewById(R.id.create_network_engine);
    engineNameView.setText("");
    final Runnable createEngine = new Runnable() {
        public void run() {
            String engineName = engineNameView.getText().toString();
            String sep = File.separator;
            String pathName = Environment.getExternalStorageDirectory() + sep + engineDir + sep + engineName;
            File file = new File(pathName);
            boolean nameOk = true;
            int errMsg = -1;
            if (engineName.contains("/")) {
                nameOk = false;
                errMsg = R.string.slash_not_allowed;
            } else if (internalEngine(engineName) || file.exists()) {
                nameOk = false;
                errMsg = R.string.engine_name_in_use;
            }
            if (!nameOk) {
                Toast.makeText(getApplicationContext(), errMsg, Toast.LENGTH_LONG).show();
                removeDialog(NETWORK_ENGINE_DIALOG);
                showDialog(NETWORK_ENGINE_DIALOG);
                return;
            }
            networkEngineToConfig = pathName;
            removeDialog(NETWORK_ENGINE_CONFIG_DIALOG);
            showDialog(NETWORK_ENGINE_CONFIG_DIALOG);
        }
    };
    builder.setPositiveButton(android.R.string.ok, new Dialog.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            createEngine.run();
        }
    });
    builder.setNegativeButton(R.string.cancel, new Dialog.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            removeDialog(NETWORK_ENGINE_DIALOG);
            showDialog(NETWORK_ENGINE_DIALOG);
        }
    });
    builder.setOnCancelListener(new Dialog.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            removeDialog(NETWORK_ENGINE_DIALOG);
            showDialog(NETWORK_ENGINE_DIALOG);
        }
    });

    final Dialog dialog = builder.create();
    engineNameView.setOnKeyListener(new OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                createEngine.run();
                dialog.cancel();
                return true;
            }
            return false;
        }
    });
    return dialog;
}

From source file:edu.mit.viral.shen.DroidFish.java

private final Dialog networkEngineConfigDialog() {
    View content = View.inflate(this, R.layout.network_engine_config, null);
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setView(content);//from  ww w.j  av  a2s . co  m
    builder.setTitle(R.string.configure_network_engine);
    final EditText hostNameView = (EditText) content.findViewById(R.id.network_engine_host);
    final EditText portView = (EditText) content.findViewById(R.id.network_engine_port);
    String hostName = "";
    String port = "0";
    try {
        String[] lines = Util.readFile(networkEngineToConfig);
        if ((lines.length >= 1) && lines[0].equals("NETE")) {
            if (lines.length > 1)
                hostName = lines[1];
            if (lines.length > 2)
                port = lines[2];
        }
    } catch (IOException e1) {
    }
    hostNameView.setText(hostName);
    portView.setText(port);
    final Runnable writeConfig = new Runnable() {
        public void run() {
            String hostName = hostNameView.getText().toString();
            String port = portView.getText().toString();
            try {
                FileWriter fw = new FileWriter(new File(networkEngineToConfig), false);
                fw.write("NETE\n");
                fw.write(hostName);
                fw.write("\n");
                fw.write(port);
                fw.write("\n");
                fw.close();
                setEngineOptions(true);
            } catch (IOException e) {
                Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
            }
        }
    };
    builder.setPositiveButton(android.R.string.ok, new Dialog.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            writeConfig.run();
            removeDialog(NETWORK_ENGINE_DIALOG);
            showDialog(NETWORK_ENGINE_DIALOG);
        }
    });
    builder.setNegativeButton(R.string.cancel, new Dialog.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            removeDialog(NETWORK_ENGINE_DIALOG);
            showDialog(NETWORK_ENGINE_DIALOG);
        }
    });
    builder.setOnCancelListener(new Dialog.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            removeDialog(NETWORK_ENGINE_DIALOG);
            showDialog(NETWORK_ENGINE_DIALOG);
        }
    });
    builder.setNeutralButton(R.string.delete, new Dialog.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            removeDialog(DELETE_NETWORK_ENGINE_DIALOG);
            showDialog(DELETE_NETWORK_ENGINE_DIALOG);
        }
    });

    final Dialog dialog = builder.create();
    portView.setOnKeyListener(new OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                writeConfig.run();
                dialog.cancel();
                removeDialog(NETWORK_ENGINE_DIALOG);
                showDialog(NETWORK_ENGINE_DIALOG);
                return true;
            }
            return false;
        }
    });
    return dialog;
}

From source file:com.nttec.everychan.ui.presentation.BoardFragment.java

private void initSearchBar() {
    if (searchBarInitialized)
        return;/*from  ww  w  . j a  va2  s.  co  m*/
    final EditText field = (EditText) searchBarView.findViewById(R.id.board_search_field);
    final TextView results = (TextView) searchBarView.findViewById(R.id.board_search_result);
    if (pageType == TYPE_POSTSLIST) {
        field.setHint(R.string.search_bar_in_thread_hint);
    }
    final View.OnClickListener searchOnClickListener = new View.OnClickListener() {
        private int lastFound = -1;

        @Override
        public void onClick(View v) {
            if (v != null && v.getId() == R.id.board_search_close) {
                searchHighlightActive = false;
                adapter.notifyDataSetChanged();
                searchBarView.setVisibility(View.GONE);
            } else if (listView != null && listView.getChildCount() > 0 && adapter != null
                    && cachedSearchResults != null) {
                boolean atEnd = listView.getChildAt(listView.getChildCount() - 1).getTop()
                        + listView.getChildAt(listView.getChildCount() - 1).getHeight() == listView.getHeight();

                View topView = listView.getChildAt(0);
                if ((v == null || v.getId() == R.id.board_search_previous) && topView.getTop() < 0
                        && listView.getChildCount() > 1)
                    topView = listView.getChildAt(1);
                int currentListPosition = listView.getPositionForView(topView);

                int newResultIndex = Collections.binarySearch(cachedSearchResults, currentListPosition);
                if (newResultIndex >= 0) {
                    if (v != null) {
                        if (v.getId() == R.id.board_search_next)
                            ++newResultIndex;
                        else if (v.getId() == R.id.board_search_previous)
                            --newResultIndex;
                    }
                } else {
                    newResultIndex = -newResultIndex - 1;
                    if (v != null && v.getId() == R.id.board_search_previous)
                        --newResultIndex;
                }
                while (newResultIndex < 0)
                    newResultIndex += cachedSearchResults.size();
                newResultIndex %= cachedSearchResults.size();

                if (v != null && v.getId() == R.id.board_search_next && lastFound == newResultIndex && atEnd)
                    newResultIndex = 0;
                lastFound = newResultIndex;

                listView.setSelection(cachedSearchResults.get(newResultIndex));
                results.setText((newResultIndex + 1) + "/" + cachedSearchResults.size());
            }
        }
    };
    for (int id : new int[] { R.id.board_search_close, R.id.board_search_previous, R.id.board_search_next }) {
        searchBarView.findViewById(id).setOnClickListener(searchOnClickListener);
    }
    field.setOnKeyListener(new View.OnKeyListener() {
        private boolean searchUsingChan() {
            if (pageType != TYPE_THREADSLIST)
                return false;
            if (presentationModel != null)
                if (presentationModel.source != null)
                    if (presentationModel.source.boardModel != null)
                        if (!presentationModel.source.boardModel.searchAllowed)
                            return false;
            return true;
        }

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                if (searchUsingChan()) {
                    UrlPageModel model = new UrlPageModel();
                    model.chanName = chan.getChanName();
                    model.type = UrlPageModel.TYPE_SEARCHPAGE;
                    model.boardName = tabModel.pageModel.boardName;
                    model.searchRequest = field.getText().toString();
                    UrlHandler.open(model, activity);
                } else {
                    int highlightColor = ThemeUtils.getThemeColor(activity.getTheme(),
                            R.attr.searchHighlightBackground, Color.RED);
                    String request = field.getText().toString().toLowerCase(Locale.US);

                    if (cachedSearchRequest == null || !request.equals(cachedSearchRequest)) {
                        cachedSearchRequest = request;
                        cachedSearchResults = new ArrayList<Integer>();
                        cachedSearchHighlightedSpanables = new SparseArray<Spanned>();
                        List<PresentationItemModel> safePresentationList = presentationModel
                                .getSafePresentationList();
                        if (safePresentationList != null) {
                            for (int i = 0; i < safePresentationList.size(); ++i) {
                                PresentationItemModel model = safePresentationList.get(i);
                                if (model.hidden && !staticSettings.showHiddenItems)
                                    continue;
                                String comment = model.spannedComment.toString().toLowerCase(Locale.US)
                                        .replace('\n', ' ');
                                List<Integer> altFoundPositions = null;
                                if (model.floating) {
                                    int floatingpos = FlowTextHelper.getFloatingPosition(model.spannedComment);
                                    if (floatingpos != -1 && floatingpos < model.spannedComment.length()
                                            && model.spannedComment.charAt(floatingpos) == '\n') {
                                        String altcomment = comment.substring(0, floatingpos)
                                                + comment.substring(floatingpos + 1,
                                                        Math.min(model.spannedComment.length(),
                                                                floatingpos + request.length()));
                                        int start = 0;
                                        int curpos;
                                        while (start < altcomment.length()
                                                && (curpos = altcomment.indexOf(request, start)) != -1) {
                                            if (altFoundPositions == null)
                                                altFoundPositions = new ArrayList<Integer>();
                                            altFoundPositions.add(curpos);
                                            start = curpos + request.length();
                                        }
                                    }
                                }

                                if (comment.contains(request) || altFoundPositions != null) {
                                    cachedSearchResults.add(Integer.valueOf(i));
                                    SpannableStringBuilder spannedHighlited = new SpannableStringBuilder(
                                            safePresentationList.get(i).spannedComment);
                                    int start = 0;
                                    int curpos;
                                    while (start < comment.length()
                                            && (curpos = comment.indexOf(request, start)) != -1) {
                                        start = curpos + request.length();
                                        if (altFoundPositions != null
                                                && Collections.binarySearch(altFoundPositions, curpos) >= 0)
                                            continue;
                                        spannedHighlited.setSpan(new BackgroundColorSpan(highlightColor),
                                                curpos, curpos + request.length(),
                                                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    }
                                    if (altFoundPositions != null) {
                                        for (Integer pos : altFoundPositions) {
                                            spannedHighlited.setSpan(new BackgroundColorSpan(highlightColor),
                                                    pos, pos + request.length(),
                                                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                        }
                                    }
                                    cachedSearchHighlightedSpanables.put(i, spannedHighlited);
                                }
                            }
                        }
                    }

                    if (cachedSearchResults.size() == 0) {
                        Toast.makeText(activity, R.string.notification_not_found, Toast.LENGTH_LONG).show();
                    } else {
                        boolean firstTime = !searchHighlightActive;
                        searchHighlightActive = true;
                        adapter.notifyDataSetChanged();
                        searchBarView.findViewById(R.id.board_search_next).setVisibility(View.VISIBLE);
                        searchBarView.findViewById(R.id.board_search_previous).setVisibility(View.VISIBLE);
                        searchBarView.findViewById(R.id.board_search_result).setVisibility(View.VISIBLE);
                        searchOnClickListener
                                .onClick(firstTime ? null : searchBarView.findViewById(R.id.board_search_next));
                    }
                }
                try {
                    InputMethodManager imm = (InputMethodManager) activity
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(field.getWindowToken(), 0);
                } catch (Exception e) {
                    Logger.e(TAG, e);
                }
                return true;
            }
            return false;
        }
    });
    field.addTextChangedListener(new OnSearchTextChangedListener(this));
    field.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
    if (resources.getDimensionPixelSize(R.dimen.panel_height) < field.getMeasuredHeight())
        searchBarView.getLayoutParams().height = field.getMeasuredHeight();
    searchBarInitialized = true;
}

From source file:org.telepatch.ui.ChatActivity.java

public View createView(LayoutInflater inflater, ViewGroup container) {
    if (fragmentView == null) {
        actionBarLayer.setDisplayHomeAsUpEnabled(true, R.drawable.ic_ab_back);
        if (AndroidUtilities.isTablet()) {
            actionBarLayer.setExtraLeftMargin(4);
        }/*from  ww  w .jav  a 2 s . c o m*/
        actionBarLayer.setBackOverlay(R.layout.updating_state_layout);
        actionBarLayer.setActionBarMenuOnItemClick(new ActionBarLayer.ActionBarMenuOnItemClick() {
            @Override
            public void onItemClick(int id) {
                if (id == -1) {
                    finishFragment();
                } else if (id == -2) {
                    selectedMessagesIds.clear();
                    selectedMessagesCanCopyIds.clear();
                    actionBarLayer.hideActionMode();
                    updateVisibleRows();
                } else if (id == attach_photo) {
                    try {
                        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        File image = Utilities.generatePicturePath();
                        if (image != null) {
                            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(image));
                            currentPicturePath = image.getAbsolutePath();
                        }
                        startActivityForResult(takePictureIntent, 0);
                    } catch (Exception e) {
                        FileLog.e("tmessages", e);
                    }
                } else if (id == attach_gallery) {
                    PhotoPickerActivity fragment = new PhotoPickerActivity();
                    fragment.setDelegate(new PhotoPickerActivity.PhotoPickerActivityDelegate() {
                        @Override
                        public void didSelectPhotos(ArrayList<String> photos) {
                            SendMessagesHelper.prepareSendingPhotos(photos, null, dialog_id);
                        }

                        @Override
                        public void startPhotoSelectActivity() {
                            try {
                                Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
                                photoPickerIntent.setType("image/*");
                                startActivityForResult(photoPickerIntent, 1);
                            } catch (Exception e) {
                                FileLog.e("tmessages", e);
                            }
                        }
                    });
                    presentFragment(fragment);
                } else if (id == attach_video) {
                    try {
                        Intent pickIntent = new Intent();
                        pickIntent.setType("video/*");
                        pickIntent.setAction(Intent.ACTION_GET_CONTENT);
                        pickIntent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, (long) (1024 * 1024 * 1000));
                        Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                        File video = Utilities.generateVideoPath();
                        if (video != null) {
                            if (Build.VERSION.SDK_INT >= 18) {
                                takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(video));
                            }
                            takeVideoIntent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, (long) (1024 * 1024 * 1000));
                            currentPicturePath = video.getAbsolutePath();
                        }
                        Intent chooserIntent = Intent.createChooser(pickIntent, "");
                        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { takeVideoIntent });

                        startActivityForResult(chooserIntent, 2);
                    } catch (Exception e) {
                        FileLog.e("tmessages", e);
                    }
                } else if (id == attach_location) {
                    if (!isGoogleMapsInstalled()) {
                        return;
                    }
                    LocationActivity fragment = new LocationActivity();
                    fragment.setDelegate(new LocationActivity.LocationActivityDelegate() {
                        @Override
                        public void didSelectLocation(double latitude, double longitude) {
                            SendMessagesHelper.getInstance().sendMessage(latitude, longitude, dialog_id);
                            if (chatListView != null) {
                                chatListView.setSelectionFromTop(messages.size() - 1,
                                        -100000 - chatListView.getPaddingTop());
                            }
                            if (paused) {
                                scrollToTopOnResume = true;
                            }
                        }
                    });
                    presentFragment(fragment);
                } else if (id == attach_document) {
                    DocumentSelectActivity fragment = new DocumentSelectActivity();
                    fragment.setDelegate(new DocumentSelectActivity.DocumentSelectActivityDelegate() {
                        @Override
                        public void didSelectFile(DocumentSelectActivity activity, String path) {
                            activity.finishFragment();
                            SendMessagesHelper.prepareSendingDocument(path, path, dialog_id);
                        }

                        @Override
                        public void startDocumentSelectActivity() {
                            try {
                                Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
                                photoPickerIntent.setType("*/*");
                                startActivityForResult(photoPickerIntent, 21);
                            } catch (Exception e) {
                                FileLog.e("tmessages", e);
                            }
                        }
                    });
                    presentFragment(fragment);
                } else if (id == chat_menu_avatar) {
                    if (currentUser != null) {
                        Bundle args = new Bundle();
                        args.putInt("user_id", currentUser.id);
                        if (currentEncryptedChat != null) {
                            args.putLong("dialog_id", dialog_id);
                        }
                        presentFragment(new UserProfileActivity(args));
                    } else if (currentChat != null) {
                        if (info != null && info instanceof TLRPC.TL_chatParticipantsForbidden) {
                            return;
                        }
                        int count = currentChat.participants_count;
                        if (info != null) {
                            count = info.participants.size();
                        }
                        if (count == 0 || currentChat.left || currentChat instanceof TLRPC.TL_chatForbidden) {
                            return;
                        }
                        Bundle args = new Bundle();
                        args.putInt("chat_id", currentChat.id);
                        ChatProfileActivity fragment = new ChatProfileActivity(args);
                        fragment.setChatInfo(info);
                        presentFragment(fragment);
                    }
                } else if (id == copy) {
                    String str = "";
                    ArrayList<Integer> ids = new ArrayList<Integer>(selectedMessagesCanCopyIds.keySet());
                    if (currentEncryptedChat == null) {
                        Collections.sort(ids);
                    } else {
                        Collections.sort(ids, Collections.reverseOrder());
                    }
                    for (Integer messageId : ids) {
                        MessageObject messageObject = selectedMessagesCanCopyIds.get(messageId);
                        if (str.length() != 0) {
                            str += "\n";
                        }
                        if (messageObject.messageOwner.message != null) {
                            str += messageObject.messageOwner.message;
                        } else {
                            str += messageObject.messageText;
                        }
                    }
                    if (str.length() != 0) {
                        if (Build.VERSION.SDK_INT < 11) {
                            android.text.ClipboardManager clipboard = (android.text.ClipboardManager) ApplicationLoader.applicationContext
                                    .getSystemService(Context.CLIPBOARD_SERVICE);
                            clipboard.setText(str);
                        } else {
                            android.content.ClipboardManager clipboard = (android.content.ClipboardManager) ApplicationLoader.applicationContext
                                    .getSystemService(Context.CLIPBOARD_SERVICE);
                            android.content.ClipData clip = android.content.ClipData.newPlainText("label", str);
                            clipboard.setPrimaryClip(clip);
                        }
                    }
                    selectedMessagesIds.clear();
                    selectedMessagesCanCopyIds.clear();
                    actionBarLayer.hideActionMode();
                    updateVisibleRows();
                } else if (id == delete) {
                    ArrayList<Integer> ids = new ArrayList<Integer>(selectedMessagesIds.keySet());
                    ArrayList<Long> random_ids = null;
                    if (currentEncryptedChat != null) {
                        random_ids = new ArrayList<Long>();
                        for (HashMap.Entry<Integer, MessageObject> entry : selectedMessagesIds.entrySet()) {
                            MessageObject msg = entry.getValue();
                            if (msg.messageOwner.random_id != 0 && msg.type != 10) {
                                random_ids.add(msg.messageOwner.random_id);
                            }
                        }
                    }
                    //MessagesController.getInstance().deleteMessages(ids, random_ids, currentEncryptedChat);
                    //TODO qui utilizzo un mio metodo per cancellare i messaggi, cosi' prima mostro un alert
                    deleteMessages(ids, random_ids, currentEncryptedChat);
                    actionBarLayer.hideActionMode();
                } else if (id == forward) {
                    Bundle args = new Bundle();
                    args.putBoolean("onlySelect", true);
                    args.putBoolean("serverOnly", true);
                    args.putString("selectAlertString",
                            LocaleController.getString("ForwardMessagesTo", R.string.ForwardMessagesTo));
                    args.putString("selectAlertStringGroup", LocaleController
                            .getString("ForwardMessagesToGroup", R.string.ForwardMessagesToGroup));
                    MessagesActivity fragment = new MessagesActivity(args);
                    fragment.setDelegate(ChatActivity.this);
                    presentFragment(fragment);
                }
            }
        });

        updateSubtitle();

        if (currentEncryptedChat != null) {
            actionBarLayer.setTitleIcon(R.drawable.ic_lock_white, AndroidUtilities.dp(4));
        } else if (currentChat != null && currentChat.id < 0) {
            actionBarLayer.setTitleIcon(R.drawable.broadcast2, AndroidUtilities.dp(4));
        }

        ActionBarMenu menu = actionBarLayer.createMenu();

        if (currentEncryptedChat != null) {
            timeItem = menu.addItemResource(chat_enc_timer, R.layout.chat_header_enc_layout);
        }

        //TODO aggiungo il pulsante di ricerca
        item_search = menu.addItem(chat_menu_search, R.drawable.ic_ab_search);
        item_search.setIsSearchField(true)
                .setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() {
                    @Override
                    public void onSearchExpand() {
                        searching = true;
                    }

                    @Override
                    public void onSearchCollapse() {
                        searching = false;
                        //MessagesController.getInstance().loadMessages(dialog_id, 0, 20, maxMessageId, !cacheEndReaced, minDate, classGuid, false, false);
                        //NotificationCenter.getInstance().postNotificationName(dialogsNeedReload);

                    }

                    @Override
                    public void onTextChanged(final EditText editText) {
                        editText.requestFocus();
                        editText.setOnKeyListener(new View.OnKeyListener() {

                            public boolean onKey(View v, int keyCode, KeyEvent event) {
                                boolean result = false;
                                // se l'evento e' un "tasto premuto" sul tasto enter
                                if ((event.getAction() == KeyEvent.ACTION_DOWN)
                                        && (keyCode == KeyEvent.KEYCODE_ENTER)) {

                                    //fai azione
                                    if (!editText.getText().toString().equals("")) {
                                        searchMessages(dialog_id, editText.getText().toString(),
                                                new FutureSearch());
                                        try {
                                            presentFragment(new SearchResultsActivity(
                                                    doSearchAndBlock(dialog_id, editText.getText().toString()),
                                                    getArguments()));
                                        } catch (ExecutionException e) {
                                            e.printStackTrace();
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        } catch (NullPointerException e) {
                                            Log.e("xela92",
                                                    "NullPointerException. Forse la connessione di rete e' assente? La ricerca  stata annullata. ");
                                            e.printStackTrace();
                                        }
                                    }
                                    result = true;
                                }
                                return result;
                            }
                        });
                    }

                });

        ActionBarMenuItem item = menu.addItem(chat_menu_attach, R.drawable.ic_ab_attach);
        item.addSubItem(attach_photo, LocaleController.getString("ChatTakePhoto", R.string.ChatTakePhoto),
                R.drawable.ic_attach_photo);
        item.addSubItem(attach_gallery, LocaleController.getString("ChatGallery", R.string.ChatGallery),
                R.drawable.ic_attach_gallery);
        item.addSubItem(attach_video, LocaleController.getString("ChatVideo", R.string.ChatVideo),
                R.drawable.ic_attach_video);
        item.addSubItem(attach_document, LocaleController.getString("ChatDocument", R.string.ChatDocument),
                R.drawable.ic_ab_doc);
        item.addSubItem(attach_location, LocaleController.getString("ChatLocation", R.string.ChatLocation),
                R.drawable.ic_attach_location);
        menuItem = item;

        actionModeViews.clear();

        final ActionBarMenu actionMode = actionBarLayer.createActionMode();
        actionModeViews.add(actionMode.addItem(-2, R.drawable.ic_ab_done_gray, R.drawable.bar_selector_mode));

        FrameLayout layout = new FrameLayout(actionMode.getContext());
        layout.setBackgroundColor(0xffe5e5e5);
        actionMode.addView(layout);
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) layout.getLayoutParams();
        layoutParams.width = AndroidUtilities.dp(1);
        layoutParams.height = LinearLayout.LayoutParams.MATCH_PARENT;
        layoutParams.topMargin = AndroidUtilities.dp(12);
        layoutParams.bottomMargin = AndroidUtilities.dp(12);
        layoutParams.gravity = Gravity.CENTER_VERTICAL;
        layout.setLayoutParams(layoutParams);
        actionModeViews.add(layout);

        selectedMessagesCountTextView = new TextView(actionMode.getContext());
        selectedMessagesCountTextView.setTextSize(18);
        selectedMessagesCountTextView.setTextColor(0xff000000);
        selectedMessagesCountTextView.setSingleLine(true);
        selectedMessagesCountTextView.setLines(1);
        selectedMessagesCountTextView.setEllipsize(TextUtils.TruncateAt.END);
        selectedMessagesCountTextView.setPadding(AndroidUtilities.dp(11), 0, 0, 0);
        selectedMessagesCountTextView.setGravity(Gravity.CENTER_VERTICAL);
        selectedMessagesCountTextView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        actionMode.addView(selectedMessagesCountTextView);
        layoutParams = (LinearLayout.LayoutParams) selectedMessagesCountTextView.getLayoutParams();
        layoutParams.weight = 1;
        layoutParams.width = 0;
        layoutParams.height = LinearLayout.LayoutParams.MATCH_PARENT;
        selectedMessagesCountTextView.setLayoutParams(layoutParams);

        if (currentEncryptedChat == null) {
            actionModeViews
                    .add(actionMode.addItem(copy, R.drawable.ic_ab_fwd_copy, R.drawable.bar_selector_mode));
            actionModeViews.add(
                    actionMode.addItem(forward, R.drawable.ic_ab_fwd_forward, R.drawable.bar_selector_mode));
            actionModeViews
                    .add(actionMode.addItem(delete, R.drawable.ic_ab_fwd_delete, R.drawable.bar_selector_mode));
        } else {
            actionModeViews
                    .add(actionMode.addItem(copy, R.drawable.ic_ab_fwd_copy, R.drawable.bar_selector_mode));
            actionModeViews
                    .add(actionMode.addItem(delete, R.drawable.ic_ab_fwd_delete, R.drawable.bar_selector_mode));
        }
        actionMode.getItem(copy)
                .setVisibility(selectedMessagesCanCopyIds.size() != 0 ? View.VISIBLE : View.GONE);

        View avatarLayout = menu.addItemResource(chat_menu_avatar, R.layout.chat_header_layout);
        avatarImageView = (BackupImageView) avatarLayout.findViewById(R.id.chat_avatar_image);
        avatarImageView.processDetach = false;
        checkActionBarMenu();

        fragmentView = inflater.inflate(R.layout.chat_layout, container, false);

        View contentView = fragmentView.findViewById(R.id.chat_layout);
        TextView emptyView = (TextView) fragmentView.findViewById(R.id.searchEmptyView);
        emptyViewContainer = fragmentView.findViewById(R.id.empty_view);
        emptyViewContainer.setVisibility(View.GONE);
        emptyViewContainer.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        emptyView.setText(LocaleController.getString("NoMessages", R.string.NoMessages));
        chatListView = (LayoutListView) fragmentView.findViewById(R.id.chat_list_view);
        chatListView.setAdapter(chatAdapter = new ChatAdapter(getParentActivity()));
        topPanel = fragmentView.findViewById(R.id.top_panel);
        topPlaneClose = (ImageView) fragmentView.findViewById(R.id.top_plane_close);
        topPanelText = (TextView) fragmentView.findViewById(R.id.top_panel_text);
        bottomOverlay = fragmentView.findViewById(R.id.bottom_overlay);
        bottomOverlayText = (TextView) fragmentView.findViewById(R.id.bottom_overlay_text);
        bottomOverlayChat = fragmentView.findViewById(R.id.bottom_overlay_chat);
        progressView = fragmentView.findViewById(R.id.progressLayout);
        pagedownButton = fragmentView.findViewById(R.id.pagedown_button);
        pagedownButton.setVisibility(View.GONE);

        View progressViewInner = progressView.findViewById(R.id.progressLayoutInner);

        updateContactStatus();

        SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig",
                Activity.MODE_PRIVATE);
        int selectedBackground = preferences.getInt("selectedBackground", 1000001);
        int selectedColor = preferences.getInt("selectedColor", 0);
        if (selectedColor != 0) {
            contentView.setBackgroundColor(selectedColor);
            chatListView.setCacheColorHint(selectedColor);
        } else {
            chatListView.setCacheColorHint(0);
            try {
                if (selectedBackground == 1000001) {
                    ((SizeNotifierRelativeLayout) contentView).setBackgroundImage(R.drawable.background_hd);
                } else {
                    File toFile = new File(ApplicationLoader.applicationContext.getFilesDir(), "wallpaper.jpg");
                    if (toFile.exists()) {
                        if (ApplicationLoader.cachedWallpaper != null) {
                            ((SizeNotifierRelativeLayout) contentView)
                                    .setBackgroundImage(ApplicationLoader.cachedWallpaper);
                        } else {
                            Drawable drawable = Drawable.createFromPath(toFile.getAbsolutePath());
                            if (drawable != null) {
                                ((SizeNotifierRelativeLayout) contentView).setBackgroundImage(drawable);
                                ApplicationLoader.cachedWallpaper = drawable;
                            } else {
                                contentView.setBackgroundColor(-2693905);
                                chatListView.setCacheColorHint(-2693905);
                            }
                        }
                        isCustomTheme = true;
                    } else {
                        ((SizeNotifierRelativeLayout) contentView).setBackgroundImage(R.drawable.background_hd);
                    }
                }
            } catch (Exception e) {
                contentView.setBackgroundColor(-2693905);
                chatListView.setCacheColorHint(-2693905);
                FileLog.e("tmessages", e);
            }
        }

        if (currentEncryptedChat != null) {
            emptyView.setVisibility(View.GONE);
            View secretChatPlaceholder = contentView.findViewById(R.id.secret_placeholder);
            secretChatPlaceholder.setVisibility(View.VISIBLE);
            if (isCustomTheme) {
                secretChatPlaceholder.setBackgroundResource(R.drawable.system_black);
            } else {
                secretChatPlaceholder.setBackgroundResource(R.drawable.system_blue);
            }
            secretViewStatusTextView = (TextView) contentView.findViewById(R.id.invite_text);
            secretChatPlaceholder.setPadding(AndroidUtilities.dp(16), AndroidUtilities.dp(12),
                    AndroidUtilities.dp(16), AndroidUtilities.dp(12));

            View v = contentView.findViewById(R.id.secret_placeholder);
            v.setVisibility(View.VISIBLE);

            if (currentEncryptedChat.admin_id == UserConfig.getClientUserId()) {
                if (currentUser.first_name.length() > 0) {
                    secretViewStatusTextView
                            .setText(LocaleController.formatString("EncryptedPlaceholderTitleOutgoing",
                                    R.string.EncryptedPlaceholderTitleOutgoing, currentUser.first_name));
                } else {
                    secretViewStatusTextView
                            .setText(LocaleController.formatString("EncryptedPlaceholderTitleOutgoing",
                                    R.string.EncryptedPlaceholderTitleOutgoing, currentUser.last_name));
                }
            } else {
                if (currentUser.first_name.length() > 0) {
                    secretViewStatusTextView
                            .setText(LocaleController.formatString("EncryptedPlaceholderTitleIncoming",
                                    R.string.EncryptedPlaceholderTitleIncoming, currentUser.first_name));
                } else {
                    secretViewStatusTextView
                            .setText(LocaleController.formatString("EncryptedPlaceholderTitleIncoming",
                                    R.string.EncryptedPlaceholderTitleIncoming, currentUser.last_name));
                }
            }

            updateSecretStatus();
        }

        if (isCustomTheme) {
            progressViewInner.setBackgroundResource(R.drawable.system_loader2);
            emptyView.setBackgroundResource(R.drawable.system_black);
        } else {
            progressViewInner.setBackgroundResource(R.drawable.system_loader1);
            emptyView.setBackgroundResource(R.drawable.system_blue);
        }
        emptyView.setPadding(AndroidUtilities.dp(7), AndroidUtilities.dp(1), AndroidUtilities.dp(7),
                AndroidUtilities.dp(1));

        if (currentUser != null && (currentUser.id / 1000 == 333 || currentUser.id % 1000 == 0)) {
            emptyView.setText(LocaleController.getString("GotAQuestion", R.string.GotAQuestion));
        }

        chatListView.setOnItemLongClickListener(onItemLongClickListener);
        chatListView.setOnItemClickListener(onItemClickListener);

        final Rect scrollRect = new Rect();

        chatListView.setOnInterceptTouchEventListener(new LayoutListView.OnInterceptTouchEventListener() {
            @Override
            public boolean onInterceptTouchEvent(MotionEvent event) {
                if (actionBarLayer.isActionModeShowed()) {
                    return false;
                }
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    int x = (int) event.getX();
                    int y = (int) event.getY();
                    int count = chatListView.getChildCount();
                    Rect rect = new Rect();
                    for (int a = 0; a < count; a++) {
                        View view = chatListView.getChildAt(a);
                        int top = view.getTop();
                        int bottom = view.getBottom();
                        view.getLocalVisibleRect(rect);
                        if (top > y || bottom < y) {
                            continue;
                        }
                        if (!(view instanceof ChatMediaCell)) {
                            break;
                        }
                        final ChatMediaCell cell = (ChatMediaCell) view;
                        final MessageObject messageObject = cell.getMessageObject();
                        if (messageObject == null || !messageObject.isSecretPhoto()
                                || !cell.getPhotoImage().isInsideImage(x, y - top)) {
                            break;
                        }
                        File file = FileLoader.getPathToMessage(messageObject.messageOwner);
                        if (!file.exists()) {
                            break;
                        }
                        startX = x;
                        startY = y;
                        chatListView.setOnItemClickListener(null);
                        openSecretPhotoRunnable = new Runnable() {
                            @Override
                            public void run() {
                                if (openSecretPhotoRunnable == null) {
                                    return;
                                }
                                chatListView.requestDisallowInterceptTouchEvent(true);
                                chatListView.setOnItemLongClickListener(null);
                                chatListView.setLongClickable(false);
                                openSecretPhotoRunnable = null;
                                if (sendSecretMessageRead(messageObject)) {
                                    cell.invalidate();
                                }
                                SecretPhotoViewer.getInstance().setParentActivity(getParentActivity());
                                SecretPhotoViewer.getInstance().openPhoto(messageObject);
                            }
                        };
                        AndroidUtilities.RunOnUIThread(openSecretPhotoRunnable, 100);
                        return true;
                    }
                }
                return false;
            }
        });

        chatListView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (openSecretPhotoRunnable != null || SecretPhotoViewer.getInstance().isVisible()) {
                    if (event.getAction() == MotionEvent.ACTION_UP
                            || event.getAction() == MotionEvent.ACTION_CANCEL
                            || event.getAction() == MotionEvent.ACTION_POINTER_UP) {
                        AndroidUtilities.RunOnUIThread(new Runnable() {
                            @Override
                            public void run() {
                                chatListView.setOnItemClickListener(onItemClickListener);
                            }
                        }, 150);
                        if (openSecretPhotoRunnable != null) {
                            AndroidUtilities.CancelRunOnUIThread(openSecretPhotoRunnable);
                            openSecretPhotoRunnable = null;
                            try {
                                Toast.makeText(v.getContext(),
                                        LocaleController.getString("PhotoTip", R.string.PhotoTip),
                                        Toast.LENGTH_SHORT).show();
                            } catch (Exception e) {
                                FileLog.e("tmessages", e);
                            }
                        } else {
                            if (SecretPhotoViewer.getInstance().isVisible()) {
                                AndroidUtilities.RunOnUIThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        chatListView.setOnItemLongClickListener(onItemLongClickListener);
                                        chatListView.setLongClickable(true);
                                    }
                                });
                                SecretPhotoViewer.getInstance().closePhoto();
                            }
                        }
                    } else if (event.getAction() != MotionEvent.ACTION_DOWN) {
                        if (SecretPhotoViewer.getInstance().isVisible()) {
                            return true;
                        } else if (openSecretPhotoRunnable != null) {
                            if (event.getAction() == MotionEvent.ACTION_MOVE) {
                                if (Math.hypot(startX - event.getX(), startY - event.getY()) > AndroidUtilities
                                        .dp(5)) {
                                    AndroidUtilities.CancelRunOnUIThread(openSecretPhotoRunnable);
                                    openSecretPhotoRunnable = null;
                                }
                            } else {
                                AndroidUtilities.CancelRunOnUIThread(openSecretPhotoRunnable);
                                openSecretPhotoRunnable = null;
                            }
                        }
                    }
                }
                return false;
            }
        });

        chatListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            @Override
            public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount,
                    int totalItemCount) {
                if (visibleItemCount > 0) {
                    if (firstVisibleItem <= 10) {
                        if (!endReached && !loading) {
                            if (messagesByDays.size() != 0) {
                                MessagesController.getInstance().loadMessages(dialog_id, 20, maxMessageId,
                                        !cacheEndReaced, minDate, classGuid, false, false, null);
                            } else {
                                MessagesController.getInstance().loadMessages(dialog_id, 20, 0, !cacheEndReaced,
                                        minDate, classGuid, false, false, null);
                            }
                            loading = true;
                        }
                    }
                    if (firstVisibleItem + visibleItemCount >= totalItemCount - 6) {
                        if (!unread_end_reached && !loadingForward) {
                            MessagesController.getInstance().loadMessages(dialog_id, 20, minMessageId, true,
                                    maxDate, classGuid, false, true, null);
                            loadingForward = true;
                        }
                    }
                    if (firstVisibleItem + visibleItemCount == totalItemCount && unread_end_reached) {
                        showPagedownButton(false, true);
                    }
                }
                for (int a = 0; a < visibleItemCount; a++) {
                    View view = absListView.getChildAt(a);
                    if (view instanceof ChatMessageCell) {
                        ChatMessageCell messageCell = (ChatMessageCell) view;
                        messageCell.getLocalVisibleRect(scrollRect);
                        messageCell.setVisiblePart(scrollRect.top, scrollRect.bottom - scrollRect.top);
                    }
                }
            }
        });

        bottomOverlayChatText = (TextView) fragmentView.findViewById(R.id.bottom_overlay_chat_text);
        TextView textView = (TextView) fragmentView.findViewById(R.id.secret_title);
        textView.setText(
                LocaleController.getString("EncryptedDescriptionTitle", R.string.EncryptedDescriptionTitle));
        textView = (TextView) fragmentView.findViewById(R.id.secret_description1);
        textView.setText(LocaleController.getString("EncryptedDescription1", R.string.EncryptedDescription1));
        textView = (TextView) fragmentView.findViewById(R.id.secret_description2);
        textView.setText(LocaleController.getString("EncryptedDescription2", R.string.EncryptedDescription2));
        textView = (TextView) fragmentView.findViewById(R.id.secret_description3);
        textView.setText(LocaleController.getString("EncryptedDescription3", R.string.EncryptedDescription3));
        textView = (TextView) fragmentView.findViewById(R.id.secret_description4);
        textView.setText(LocaleController.getString("EncryptedDescription4", R.string.EncryptedDescription4));

        if (loading && messages.isEmpty()) {
            progressView.setVisibility(View.VISIBLE);
            chatListView.setEmptyView(null);
        } else {
            progressView.setVisibility(View.GONE);
            chatListView.setEmptyView(emptyViewContainer);
        }

        pagedownButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                scrollToLastMessage();
            }
        });

        bottomOverlayChat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (getParentActivity() == null) {
                    return;
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                if (currentUser != null && userBlocked) {
                    builder.setMessage(LocaleController.getString("AreYouSureUnblockContact",
                            R.string.AreYouSureUnblockContact));
                    builder.setPositiveButton(LocaleController.getString("OK", R.string.OK),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    MessagesController.getInstance().unblockUser(currentUser.id);
                                }
                            });
                } else {
                    builder.setMessage(LocaleController.getString("AreYouSureDeleteThisChat",
                            R.string.AreYouSureDeleteThisChat));
                    builder.setPositiveButton(LocaleController.getString("OK", R.string.OK),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    MessagesController.getInstance().deleteDialog(dialog_id, 0, false);
                                    finishFragment();
                                }
                            });
                }
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                showAlertDialog(builder);
            }
        });

        updateBottomOverlay();

        chatActivityEnterView.setContainerView(getParentActivity(), fragmentView);
    } else {
        ViewGroup parent = (ViewGroup) fragmentView.getParent();
        if (parent != null) {
            parent.removeView(fragmentView);
        }
    }
    return fragmentView;
}