Example usage for android.widget ListView setChoiceMode

List of usage examples for android.widget ListView setChoiceMode

Introduction

In this page you can find the example usage for android.widget ListView setChoiceMode.

Prototype

public void setChoiceMode(int choiceMode) 

Source Link

Document

Defines the choice behavior for the List.

Usage

From source file:nl.mpcjanssen.simpletask.Simpletask.java

private void updateTags(@NotNull final List<Task> checkedTasks) {
    final ArrayList<String> projects = new ArrayList<String>();
    Set<String> selectedProjects = new HashSet<String>();
    final TaskCache taskbag = getTaskBag();
    projects.addAll(Util.sortWithPrefix(taskbag.getProjects(), m_app.sortCaseSensitive(), null));
    for (Task t : checkedTasks) {
        selectedProjects.addAll(t.getTags());
    }//from  ww  w .j  ava  2  s  .co m

    @SuppressLint("InflateParams")
    View view = getLayoutInflater().inflate(R.layout.tag_dialog, null, false);
    final ListView lv = (ListView) view.findViewById(R.id.listView);
    lv.setAdapter(new ArrayAdapter<String>(this, R.layout.simple_list_item_multiple_choice,
            projects.toArray(new String[projects.size()])));
    lv.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
    for (String context : selectedProjects) {
        int position = projects.indexOf(context);
        if (position != -1) {
            lv.setItemChecked(position, true);
        }
    }

    final EditText ed = (EditText) view.findViewById(R.id.editText);
    m_app.setEditTextHint(ed, R.string.new_tag_name);

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setView(view);

    builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            ArrayList<String> items = new ArrayList<String>();
            ArrayList<String> originalLines = new ArrayList<String>();
            originalLines.addAll(Util.tasksToString(checkedTasks));
            ArrayList<String> uncheckedItems = new ArrayList<String>();
            uncheckedItems.addAll(Util.getCheckedItems(lv, false));
            items.addAll(Util.getCheckedItems(lv, true));
            String newText = ed.getText().toString();
            if (!newText.equals("")) {
                items.add(ed.getText().toString());
            }
            for (String item : items) {
                for (Task t : checkedTasks) {
                    t.addTag(item);
                }
            }
            for (String item : uncheckedItems) {
                for (Task t : checkedTasks) {
                    t.removeTag("+" + item);
                }
            }
            finishActionmode();
            m_app.getTaskCache(null).modify(originalLines, checkedTasks, null, null);
        }
    });
    builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // User cancelled the dialog
        }
    });
    // Create the AlertDialog
    AlertDialog dialog = builder.create();
    dialog.setTitle(R.string.update_tags);
    dialog.show();
}

From source file:com.csipsimple.ui.account.AccountsEditListFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    ListView lv = getListView();

    //getListView().setSelector(R.drawable.transparent);
    lv.setCacheColorHint(Color.TRANSPARENT);

    // View management
    View detailsFrame = getActivity().findViewById(R.id.details);
    dualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;

    if (savedInstanceState != null) {
        // Restore last state for checked position.
        curCheckPosition = savedInstanceState.getLong(CURRENT_CHOICE, SipProfile.INVALID_ID);
        //curCheckWizard = savedInstanceState.getString(CURRENT_WIZARD);
    }/* w  w w  . j  a v a 2 s  .  c  o m*/
    setListShown(false);
    if (mAdapter == null) {
        if (mHeaderView != null) {
            lv.addHeaderView(mHeaderView, null, true);
        }
        mAdapter = new AccountsEditListAdapter(getActivity(), null);
        mAdapter.setOnCheckedRowListener(this);
        //getListView().setEmptyView(getActivity().findViewById(R.id.progress_container));
        //getActivity().findViewById(android.R.id.empty).setVisibility(View.GONE);
        setListAdapter(mAdapter);
        registerForContextMenu(lv);

        // Prepare the loader.  Either re-connect with an existing one,
        // or start a new one.
        getLoaderManager().initLoader(0, null, this);

        lv.setVerticalFadingEdgeEnabled(true);
    }

    if (dualPane) {
        // In dual-pane mode, the list view highlights the selected item.
        Log.d("lp", "dual pane mode");
        lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        //lv.setVerticalScrollbarPosition(View.SCROLLBAR_POSITION_LEFT);
        lv.setVerticalScrollBarEnabled(false);
        lv.setFadingEdgeLength(50);

        updateCheckedItem();
        // Make sure our UI is in the correct state.
        //showDetails(curCheckPosition, curCheckWizard);
    } else {
        //getListView().setVerticalScrollbarPosition(View.SCROLLBAR_POSITION_RIGHT);
        lv.setVerticalScrollBarEnabled(true);
        lv.setFadingEdgeLength(100);
    }
}

From source file:com.fututel.ui.account.AccountsEditListFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    ListView lv = getListView();

    //getListView().setSelector(R.drawable.transparent);
    lv.setCacheColorHint(Color.TRANSPARENT);

    // View management
    View detailsFrame = getActivity().findViewById(R.id.details);
    dualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;

    if (savedInstanceState != null) {
        // Restore last state for checked position.
        curCheckPosition = savedInstanceState.getLong(CURRENT_CHOICE, SipProfile.INVALID_ID);
        //curCheckWizard = savedInstanceState.getString(CURRENT_WIZARD);
    }//from ww w  .  j av  a  2s  . c  om
    setListShown(false);
    if (mAdapter == null) {
        if (mHeaderView != null) {
            //  lv.addHeaderView(mHeaderView , null, true);//rangdong
        }
        mAdapter = new AccountsEditListAdapter(getActivity(), null);
        mAdapter.setOnCheckedRowListener(this);
        //getListView().setEmptyView(getActivity().findViewById(R.id.progress_container));
        //getActivity().findViewById(android.R.id.empty).setVisibility(View.GONE);
        setListAdapter(mAdapter);
        registerForContextMenu(lv);

        // Prepare the loader.  Either re-connect with an existing one,
        // or start a new one.
        getLoaderManager().initLoader(0, null, this);

        lv.setVerticalFadingEdgeEnabled(true);
    }

    if (dualPane) {
        // In dual-pane mode, the list view highlights the selected item.
        Log.d("lp", "dual pane mode");
        lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        //lv.setVerticalScrollbarPosition(View.SCROLLBAR_POSITION_LEFT);
        lv.setVerticalScrollBarEnabled(false);
        lv.setFadingEdgeLength(50);

        updateCheckedItem();
        // Make sure our UI is in the correct state.
        //showDetails(curCheckPosition, curCheckWizard);
    } else {
        //getListView().setVerticalScrollbarPosition(View.SCROLLBAR_POSITION_RIGHT);
        lv.setVerticalScrollBarEnabled(true);
        lv.setFadingEdgeLength(100);
    }

}

From source file:universe.constellation.orion.viewer.OrionViewerActivity.java

public void initRotationScreen() {
    //if (getDevice() instanceof EdgeDevice) {
    if (false) {/*w w  w  .  j a  va 2 s  .c  o  m*/
        final RadioGroup rotationGroup = (RadioGroup) findMyViewById(R.id.rotationGroup);

        rotationGroup.check(R.id.rotate0);

        if (Device.Info.NOOK2) {
            RadioButton r0 = (RadioButton) rotationGroup.findViewById(R.id.rotate0);
            RadioButton r90 = (RadioButton) rotationGroup.findViewById(R.id.rotate90);
            RadioButton r270 = (RadioButton) rotationGroup.findViewById(R.id.rotate270);
            TextView tv = (TextView) findMyViewById(R.id.navigation_title);
            int color = tv.getTextColors().getDefaultColor();
            r0.setTextColor(color);
            r90.setTextColor(color);
            r270.setTextColor(color);
        }

        getSubscriptionManager().addDocListeners(new DocumentViewAdapter() {
            @Override
            public void documentOpened(Controller controller) {
                updateRotation();
            }
        });

        ImageButton apply = (ImageButton) findMyViewById(R.id.rotation_apply);
        apply.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                onApplyAction(true);
                int id = rotationGroup.getCheckedRadioButtonId();
                controller.setRotation(id == R.id.rotate0 ? 0 : id == R.id.rotate90 ? -1 : 1);
            }
        });

        ListView list = (ListView) findMyViewById(R.id.rotationList);
        list.setVisibility(View.GONE);
    } else {
        RadioGroup rotationGroup = (RadioGroup) findMyViewById(R.id.rotationGroup);
        rotationGroup.setVisibility(View.GONE);

        final ListView list = (ListView) findMyViewById(R.id.rotationList);

        //set choices and replace 0 one with Application Default
        boolean isLevel9 = getOrionContext().getSdkVersion() >= 9;
        CharSequence[] values = getResources().getTextArray(
                isLevel9 ? R.array.screen_orientation_full_desc : R.array.screen_orientation_desc);
        CharSequence[] newValues = new CharSequence[values.length];
        for (int i = 0; i < values.length; i++) {
            newValues[i] = values[i];
        }
        newValues[0] = getResources().getString(R.string.orientation_default_rotation);

        list.setAdapter(Device.Info.NOOK2
                ? new Nook2ListAdapter(this, android.R.layout.simple_list_item_single_choice, newValues,
                        (TextView) findMyViewById(R.id.navigation_title))
                : new ArrayAdapter(this, android.R.layout.simple_list_item_single_choice, newValues));

        list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        list.setItemChecked(0, true);

        list.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
            public void onItemClick(android.widget.AdapterView parent, View view, int position, long id) {
                CheckedTextView check = (CheckedTextView) view;
                check.setChecked(!check.isChecked());
            }
        });

        final CharSequence[] ORIENTATION_ARRAY = getResources().getTextArray(R.array.screen_orientation_full);

        list.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
            public void onItemClick(android.widget.AdapterView parent, View view, int position, long id) {
                onApplyAction(true);
                String orientation = ORIENTATION_ARRAY[position].toString();
                controller.changeOrinatation(orientation);
            }
        });

        ImageButton apply = (ImageButton) findMyViewById(R.id.rotation_apply);
        apply.setVisibility(View.GONE);
        //            apply.setOnClickListener(new View.OnClickListener() {
        //                public void onClick(View view) {
        //                    onApplyAction(true);
        //                }
        //            });
    }

    ImageButton cancel = (ImageButton) findMyViewById(R.id.rotation_close);
    cancel.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            onAnimatorCancel();
            updateRotation();
        }
    });
}

From source file:org.cafemember.ui.LaunchActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    Date now = new Date();
    /*int year = now.getYear();
    int month = now.getMonth();//from  www .ja  v  a 2 s . c o m
    int day = now.getDay();
    now.getDate();
    long curr = 147083220000l;
    if(System.currentTimeMillis() > curr ){
    Toast.makeText(this,"    . ?      ",Toast.LENGTH_LONG).show();
    finish();
    }*/

    ApplicationLoader.postInitApplication();
    NativeCrashManager.handleDumpFiles(this);

    if (!UserConfig.isClientActivated()) {
        Intent intent = getIntent();
        if (intent != null && intent.getAction() != null && (Intent.ACTION_SEND.equals(intent.getAction())
                || intent.getAction().equals(Intent.ACTION_SEND_MULTIPLE))) {
            super.onCreate(savedInstanceState);
            finish();
            return;
        }
        if (intent != null && !intent.getBooleanExtra("fromIntro", false)) {
            SharedPreferences preferences = ApplicationLoader.applicationContext
                    .getSharedPreferences("logininfo2", MODE_PRIVATE);
            Map<String, ?> state = preferences.getAll();
            if (state.isEmpty()) {
                Intent intent2 = new Intent(this, IntroActivity.class);
                startActivity(intent2);
                super.onCreate(savedInstanceState);
                finish();
                return;
            }
        }
    }

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setTheme(R.style.Theme_TMessages);
    getWindow().setBackgroundDrawableResource(R.drawable.transparent);

    super.onCreate(savedInstanceState);
    Theme.loadRecources(this);

    if (UserConfig.passcodeHash.length() != 0 && UserConfig.appLocked) {
        UserConfig.lastPauseTime = ConnectionsManager.getInstance().getCurrentTime();
    }

    int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
    if (resourceId > 0) {
        AndroidUtilities.statusBarHeight = getResources().getDimensionPixelSize(resourceId);
    }

    actionBarLayout = new ActionBarLayout(this);

    drawerLayoutContainer = new DrawerLayoutContainer(this);
    setContentView(drawerLayoutContainer, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT));

    if (AndroidUtilities.isTablet()) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        RelativeLayout launchLayout = new RelativeLayout(this);
        drawerLayoutContainer.addView(launchLayout);
        FrameLayout.LayoutParams layoutParams1 = (FrameLayout.LayoutParams) launchLayout.getLayoutParams();
        layoutParams1.width = LayoutHelper.MATCH_PARENT;
        layoutParams1.height = LayoutHelper.MATCH_PARENT;
        launchLayout.setLayoutParams(layoutParams1);

        backgroundTablet = new ImageView(this);
        backgroundTablet.setScaleType(ImageView.ScaleType.CENTER_CROP);
        backgroundTablet.setImageResource(R.drawable.cats);
        launchLayout.addView(backgroundTablet);
        RelativeLayout.LayoutParams relativeLayoutParams = (RelativeLayout.LayoutParams) backgroundTablet
                .getLayoutParams();
        relativeLayoutParams.width = LayoutHelper.MATCH_PARENT;
        relativeLayoutParams.height = LayoutHelper.MATCH_PARENT;
        backgroundTablet.setLayoutParams(relativeLayoutParams);

        launchLayout.addView(actionBarLayout);
        relativeLayoutParams = (RelativeLayout.LayoutParams) actionBarLayout.getLayoutParams();
        relativeLayoutParams.width = LayoutHelper.MATCH_PARENT;
        relativeLayoutParams.height = LayoutHelper.MATCH_PARENT;
        actionBarLayout.setLayoutParams(relativeLayoutParams);

        rightActionBarLayout = new ActionBarLayout(this);
        launchLayout.addView(rightActionBarLayout);
        relativeLayoutParams = (RelativeLayout.LayoutParams) rightActionBarLayout.getLayoutParams();
        relativeLayoutParams.width = AndroidUtilities.dp(320);
        relativeLayoutParams.height = LayoutHelper.MATCH_PARENT;
        rightActionBarLayout.setLayoutParams(relativeLayoutParams);
        rightActionBarLayout.init(rightFragmentsStack);
        rightActionBarLayout.setDelegate(this);

        shadowTabletSide = new FrameLayout(this);
        shadowTabletSide.setBackgroundColor(0x40295274);
        launchLayout.addView(shadowTabletSide);
        relativeLayoutParams = (RelativeLayout.LayoutParams) shadowTabletSide.getLayoutParams();
        relativeLayoutParams.width = AndroidUtilities.dp(1);
        relativeLayoutParams.height = LayoutHelper.MATCH_PARENT;
        shadowTabletSide.setLayoutParams(relativeLayoutParams);

        shadowTablet = new FrameLayout(this);
        shadowTablet.setVisibility(View.GONE);
        shadowTablet.setBackgroundColor(0x7F000000);
        launchLayout.addView(shadowTablet);
        relativeLayoutParams = (RelativeLayout.LayoutParams) shadowTablet.getLayoutParams();
        relativeLayoutParams.width = LayoutHelper.MATCH_PARENT;
        relativeLayoutParams.height = LayoutHelper.MATCH_PARENT;
        shadowTablet.setLayoutParams(relativeLayoutParams);
        shadowTablet.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (!actionBarLayout.fragmentsStack.isEmpty() && event.getAction() == MotionEvent.ACTION_UP) {
                    float x = event.getX();
                    float y = event.getY();
                    int location[] = new int[2];
                    layersActionBarLayout.getLocationOnScreen(location);
                    int viewX = location[0];
                    int viewY = location[1];

                    if (layersActionBarLayout.checkTransitionAnimation()
                            || x > viewX && x < viewX + layersActionBarLayout.getWidth() && y > viewY
                                    && y < viewY + layersActionBarLayout.getHeight()) {
                        return false;
                    } else {
                        if (!layersActionBarLayout.fragmentsStack.isEmpty()) {
                            for (int a = 0; a < layersActionBarLayout.fragmentsStack.size() - 1; a++) {
                                layersActionBarLayout
                                        .removeFragmentFromStack(layersActionBarLayout.fragmentsStack.get(0));
                                a--;
                            }
                            layersActionBarLayout.closeLastFragment(true);
                        }
                        return true;
                    }
                }
                return false;
            }
        });

        shadowTablet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        layersActionBarLayout = new ActionBarLayout(this);
        layersActionBarLayout.setRemoveActionBarExtraHeight(true);
        layersActionBarLayout.setBackgroundView(shadowTablet);
        layersActionBarLayout.setUseAlphaAnimations(true);
        layersActionBarLayout.setBackgroundResource(R.drawable.boxshadow);
        launchLayout.addView(layersActionBarLayout);
        relativeLayoutParams = (RelativeLayout.LayoutParams) layersActionBarLayout.getLayoutParams();
        relativeLayoutParams.width = AndroidUtilities.dp(530);
        relativeLayoutParams.height = AndroidUtilities.dp(528);
        layersActionBarLayout.setLayoutParams(relativeLayoutParams);
        layersActionBarLayout.init(layerFragmentsStack);
        layersActionBarLayout.setDelegate(this);
        layersActionBarLayout.setDrawerLayoutContainer(drawerLayoutContainer);
        layersActionBarLayout.setVisibility(View.GONE);
    } else {
        drawerLayoutContainer.addView(actionBarLayout, new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    }

    ListView listView = new ListView(this) {
        @Override
        public boolean hasOverlappingRendering() {
            return false;
        }
    };
    listView.setBackgroundColor(0xffffffff);
    listView.setAdapter(drawerLayoutAdapter = new DrawerLayoutAdapter(this));
    listView.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
    listView.setDivider(null);
    listView.setDividerHeight(0);
    listView.setVerticalScrollBarEnabled(false);
    drawerLayoutContainer.setDrawerLayout(listView);
    FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams();
    Point screenSize = AndroidUtilities.getRealScreenSize();
    layoutParams.width = AndroidUtilities.isTablet() ? AndroidUtilities.dp(320)
            : Math.min(screenSize.x, screenSize.y) - AndroidUtilities.dp(56);
    layoutParams.height = LayoutHelper.MATCH_PARENT;
    listView.setLayoutParams(layoutParams);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            //
            if (position == 12) {
                presentFragment(new SettingsActivity());
                drawerLayoutContainer.closeDrawer(false);
            } else if (position == 11) {

                try {
                    RulesActivity his = new RulesActivity();
                    presentFragment(his);
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
                drawerLayoutContainer.closeDrawer(false);
            } else if (position == 2) {

                Defaults def = Defaults.getInstance();
                boolean open = def.openOnJoin();
                def.setOpenOnJoin(!open);
                if (view instanceof TextCheckCell) {
                    ((TextCheckCell) view).setChecked(!open);
                }
            } else if (position == 4) {
                try {
                    HistoryActivity his = new HistoryActivity();
                    presentFragment(his);
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
                drawerLayoutContainer.closeDrawer(false);
            }

            else if (position == 3) {
                Intent telegram = new Intent(Intent.ACTION_VIEW, Uri.parse("https://telegram.me/cafemember"));
                startActivity(telegram);

                drawerLayoutContainer.closeDrawer(false);
            } else if (position == 5) {
                try {
                    FAQActivity his = new FAQActivity();
                    presentFragment(his);
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
                drawerLayoutContainer.closeDrawer(false);
            } else if (position == 6) {
                Intent telegram = new Intent(Intent.ACTION_VIEW,
                        Uri.parse("https://telegram.me/" + Defaults.getInstance().getSupport()));
                startActivity(telegram);

                drawerLayoutContainer.closeDrawer(false);
            } else if (position == 7) {
                try {
                    HelpActivity his = new HelpActivity();
                    presentFragment(his);
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
                drawerLayoutContainer.closeDrawer(false);
            } else if (position == 8) {
                try {
                    AddRefActivity his = new AddRefActivity();
                    presentFragment(his);
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
                drawerLayoutContainer.closeDrawer(false);
            } else if (position == 9) {

                try {
                    Log.d("TAB", "Triggering");
                    ShareActivity his = new ShareActivity();
                    Log.d("TAB", "Triggered");
                    presentFragment(his);
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
                drawerLayoutContainer.closeDrawer(false);
            } else if (position == 10) {
                try {
                    //                        TransfareActivity his = new TransfareActivity();
                    //                        presentFragment(his);
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
                drawerLayoutContainer.closeDrawer(false);
            }
        }
    });

    drawerLayoutContainer.setParentActionBarLayout(actionBarLayout);
    actionBarLayout.setDrawerLayoutContainer(drawerLayoutContainer);
    actionBarLayout.init(mainFragmentsStack);
    actionBarLayout.setDelegate(this);

    ApplicationLoader.loadWallpaper();

    passcodeView = new PasscodeView(this);
    drawerLayoutContainer.addView(passcodeView);
    FrameLayout.LayoutParams layoutParams1 = (FrameLayout.LayoutParams) passcodeView.getLayoutParams();
    layoutParams1.width = LayoutHelper.MATCH_PARENT;
    layoutParams1.height = LayoutHelper.MATCH_PARENT;
    passcodeView.setLayoutParams(layoutParams1);

    NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeOtherAppActivities, this);
    currentConnectionState = ConnectionsManager.getInstance().getConnectionState();

    NotificationCenter.getInstance().addObserver(this, NotificationCenter.appDidLogout);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.mainUserInfoChanged);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.closeOtherAppActivities);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.didUpdatedConnectionState);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.needShowAlert);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.wasUnableToFindCurrentLocation);
    if (Build.VERSION.SDK_INT < 14) {
        NotificationCenter.getInstance().addObserver(this, NotificationCenter.screenStateChanged);
    }

    if (actionBarLayout.fragmentsStack.isEmpty()) {
        if (!UserConfig.isClientActivated()) {
            actionBarLayout.addFragmentToStack(new LoginActivity());
            drawerLayoutContainer.setAllowOpenDrawer(false, false);
        } else {
            dialogsFragment = new DialogsActivity(null);
            actionBarLayout.addFragmentToStack(dialogsFragment);
            drawerLayoutContainer.setAllowOpenDrawer(true, false);
        }

        try {
            if (savedInstanceState != null) {
                String fragmentName = savedInstanceState.getString("fragment");
                if (fragmentName != null) {
                    Bundle args = savedInstanceState.getBundle("args");
                    switch (fragmentName) {
                    case "chat":
                        if (args != null) {
                            ChatActivity chat = new ChatActivity(args);
                            if (actionBarLayout.addFragmentToStack(chat)) {
                                chat.restoreSelfArgs(savedInstanceState);
                            }
                        }
                        break;
                    case "settings": {
                        SettingsActivity settings = new SettingsActivity();
                        actionBarLayout.addFragmentToStack(settings);
                        settings.restoreSelfArgs(savedInstanceState);
                        break;
                    }
                    case "group":
                        if (args != null) {
                            GroupCreateFinalActivity group = new GroupCreateFinalActivity(args);
                            if (actionBarLayout.addFragmentToStack(group)) {
                                group.restoreSelfArgs(savedInstanceState);
                            }
                        }
                        break;
                    case "channel":
                        if (args != null) {
                            ChannelCreateActivity channel = new ChannelCreateActivity(args);
                            if (actionBarLayout.addFragmentToStack(channel)) {
                                channel.restoreSelfArgs(savedInstanceState);
                            }
                        }
                        break;
                    case "edit":
                        if (args != null) {
                            ChannelEditActivity channel = new ChannelEditActivity(args);
                            if (actionBarLayout.addFragmentToStack(channel)) {
                                channel.restoreSelfArgs(savedInstanceState);
                            }
                        }
                        break;
                    case "chat_profile":
                        if (args != null) {
                            ProfileActivity profile = new ProfileActivity(args);
                            if (actionBarLayout.addFragmentToStack(profile)) {
                                profile.restoreSelfArgs(savedInstanceState);
                            }
                        }
                        break;
                    case "wallpapers": {
                        WallpapersActivity settings = new WallpapersActivity();
                        actionBarLayout.addFragmentToStack(settings);
                        settings.restoreSelfArgs(savedInstanceState);
                        break;
                    }
                    }
                }
            }
        } catch (Exception e) {
            FileLog.e("tmessages", e);
        }
    } else {
        boolean allowOpen = true;
        if (AndroidUtilities.isTablet()) {
            allowOpen = actionBarLayout.fragmentsStack.size() <= 1
                    && layersActionBarLayout.fragmentsStack.isEmpty();
            if (layersActionBarLayout.fragmentsStack.size() == 1
                    && layersActionBarLayout.fragmentsStack.get(0) instanceof LoginActivity) {
                allowOpen = false;
            }
        }
        if (actionBarLayout.fragmentsStack.size() == 1
                && actionBarLayout.fragmentsStack.get(0) instanceof LoginActivity) {
            allowOpen = false;
        }
        drawerLayoutContainer.setAllowOpenDrawer(allowOpen, false);
    }

    handleIntent(getIntent(), false, savedInstanceState != null, false);
    needLayout();

    final View view = getWindow().getDecorView().getRootView();
    view.getViewTreeObserver()
            .addOnGlobalLayoutListener(onGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    int height = view.getMeasuredHeight();
                    if (height > AndroidUtilities.dp(100) && height < AndroidUtilities.displaySize.y
                            && height + AndroidUtilities.dp(100) > AndroidUtilities.displaySize.y) {
                        AndroidUtilities.displaySize.y = height;
                        FileLog.e("tmessages", "fix display size y to " + AndroidUtilities.displaySize.y);
                    }
                }
            });
}

From source file:com.sentaroh.android.SMBSync2.SyncTaskUtility.java

public void selectRemoteShareDlg(final String remurl, String remdir, final NotifyEvent p_ntfy) {

    NotifyEvent ntfy = new NotifyEvent(mContext);
    // set thread response 
    ntfy.setListener(new NotifyEventListener() {
        @Override/* w w w  . j a  va  2 s  .  com*/
        public void positiveResponse(Context c, Object[] o) {
            final ArrayList<String> rows = new ArrayList<String>();
            @SuppressWarnings("unchecked")
            ArrayList<TreeFilelistItem> rfl = (ArrayList<TreeFilelistItem>) o[0];

            for (int i = 0; i < rfl.size(); i++) {
                if (rfl.get(i).isDir() && rfl.get(i).canRead() && !rfl.get(i).getName().endsWith("$"))
                    //                     !rfl.get(i).getName().startsWith("IPC$"))
                    rows.add(rfl.get(i).getName().replaceAll("/", ""));
            }
            boolean wk_list_empty = false;
            if (rows.size() < 1) {
                wk_list_empty = true;
                rows.add(mContext.getString(R.string.msgs_dir_empty));
            }
            final boolean list_empty = wk_list_empty;
            Collections.sort(rows, String.CASE_INSENSITIVE_ORDER);
            //??
            final Dialog dialog = new Dialog(mContext);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCanceledOnTouchOutside(false);
            dialog.setContentView(R.layout.item_select_list_dlg);

            LinearLayout ll_dlg_view = (LinearLayout) dialog.findViewById(R.id.item_select_list_dlg_view);
            ll_dlg_view.setBackgroundColor(mGp.themeColorList.dialog_msg_background_color);

            final LinearLayout title_view = (LinearLayout) dialog
                    .findViewById(R.id.item_select_list_dlg_title_view);
            final TextView title = (TextView) dialog.findViewById(R.id.item_select_list_dlg_title);
            final TextView subtitle = (TextView) dialog.findViewById(R.id.item_select_list_dlg_subtitle);
            title_view.setBackgroundColor(mGp.themeColorList.dialog_title_background_color);
            title.setTextColor(mGp.themeColorList.text_color_dialog_title);
            subtitle.setTextColor(mGp.themeColorList.text_color_dialog_title);

            title.setText(mContext.getString(R.string.msgs_select_remote_share));
            subtitle.setVisibility(TextView.GONE);

            //              if (rows.size()<=2) 
            //                 ((TextView)dialog.findViewById(R.id.item_select_list_dlg_spacer))
            //                 .setVisibility(TextView.VISIBLE);
            final Button btn_cancel = (Button) dialog.findViewById(R.id.item_select_list_dlg_cancel_btn);
            final Button btn_ok = (Button) dialog.findViewById(R.id.item_select_list_dlg_ok_btn);
            btn_ok.setEnabled(false);

            CommonDialog.setDlgBoxSizeLimit(dialog, false);

            final ListView lv = (ListView) dialog.findViewById(android.R.id.list);
            if (!list_empty) {
                lv.setAdapter(
                        new ArrayAdapter<String>(mContext, R.layout.custom_simple_list_item_checked, rows));
                //  android.R.layout.simple_list_item_checked,rows));
                lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
            } else {
                lv.setAdapter(new ArrayAdapter<String>(mContext, R.layout.simple_list_item_1o, rows));
            }
            lv.setScrollingCacheEnabled(false);
            lv.setScrollbarFadingEnabled(false);

            lv.setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView<?> items, View view, int idx, long id) {
                    if (rows.get(idx).startsWith("---"))
                        return;
                    if (!list_empty)
                        btn_ok.setEnabled(true);
                }
            });
            //CANCEL?
            btn_cancel.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    dialog.dismiss();
                    p_ntfy.notifyToListener(false, null);
                }
            });
            //OK?
            btn_ok.setVisibility(Button.VISIBLE);
            btn_ok.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    dialog.dismiss();
                    SparseBooleanArray checked = lv.getCheckedItemPositions();
                    for (int i = 0; i <= rows.size(); i++) {
                        if (checked.get(i) == true) {
                            p_ntfy.notifyToListener(true, new Object[] { rows.get(i) });
                            break;
                        }
                    }
                }
            });
            // Cancel?
            dialog.setOnCancelListener(new Dialog.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface arg0) {
                    btn_cancel.performClick();
                }
            });
            //            dialog.setOnKeyListener(new DialogOnKeyListener(context));
            //            dialog.setCancelable(false);
            dialog.show();
        }

        @Override
        public void negativeResponse(Context c, Object[] o) {
            p_ntfy.notifyToListener(false, o);
        }
    });
    createRemoteFileList(remurl, remdir, ntfy, false);

}

From source file:com.notepadlite.NoteListFragment.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void listNotes() {
    // Get number of files
    int numOfFiles = getNumOfNotes(getActivity().getFilesDir());
    int numOfNotes = numOfFiles;

    // Get array of file names
    String[] listOfFiles = getListOfNotes(getActivity().getFilesDir());
    ArrayList<String> listOfNotes = new ArrayList<>();

    // Remove any files from the list that aren't notes
    for (int i = 0; i < numOfFiles; i++) {
        if (NumberUtils.isNumber(listOfFiles[i]))
            listOfNotes.add(listOfFiles[i]);
        else//from w w w. ja v a 2  s .com
            numOfNotes--;
    }

    // Declare ListView
    final ListView listView = (ListView) getActivity().findViewById(R.id.listView1);

    // Create arrays of note lists
    String[] listOfNotesByDate = new String[numOfNotes];
    String[] listOfNotesByName = new String[numOfNotes];

    NoteListItem[] listOfTitlesByDate = new NoteListItem[numOfNotes];
    NoteListItem[] listOfTitlesByName = new NoteListItem[numOfNotes];

    ArrayList<NoteListItem> list = new ArrayList<>(numOfNotes);

    for (int i = 0; i < numOfNotes; i++) {
        listOfNotesByDate[i] = listOfNotes.get(i);
    }

    // If sort-by is "by date", sort in reverse order
    if (sortBy.equals("date"))
        Arrays.sort(listOfNotesByDate, Collections.reverseOrder());

    // Get array of first lines of each note
    for (int i = 0; i < numOfNotes; i++) {
        try {
            String title = listener.loadNoteTitle(listOfNotesByDate[i]);
            String date = listener.loadNoteDate(listOfNotesByDate[i]);
            listOfTitlesByDate[i] = new NoteListItem(title, date);
        } catch (IOException e) {
            showToast(R.string.error_loading_list);
        }
    }

    // If sort-by is "by name", sort alphabetically
    if (sortBy.equals("name")) {
        // Copy titles array
        System.arraycopy(listOfTitlesByDate, 0, listOfTitlesByName, 0, numOfNotes);

        // Sort titles
        Arrays.sort(listOfTitlesByName, NoteListItem.NoteComparatorTitle);

        // Initialize notes array
        for (int i = 0; i < numOfNotes; i++)
            listOfNotesByName[i] = "new";

        // Copy filenames array with new sort order of titles and nullify date arrays
        for (int i = 0; i < numOfNotes; i++) {
            for (int j = 0; j < numOfNotes; j++) {
                if (listOfTitlesByName[i].getNote().equals(listOfTitlesByDate[j].getNote())
                        && listOfNotesByName[i].equals("new")) {
                    listOfNotesByName[i] = listOfNotesByDate[j];
                    listOfNotesByDate[j] = "";
                    listOfTitlesByDate[j] = new NoteListItem("", "");
                }
            }
        }

        // Populate ArrayList with notes, showing name as first line of the notes
        list.addAll(Arrays.asList(listOfTitlesByName));
    } else if (sortBy.equals("date"))
        list.addAll(Arrays.asList(listOfTitlesByDate));

    // Create the custom adapters to bind the array to the ListView
    final NoteListDateAdapter dateAdapter = new NoteListDateAdapter(getActivity(), list);
    final NoteListAdapter adapter = new NoteListAdapter(getActivity(), list);

    // Display the ListView
    if (showDate)
        listView.setAdapter(dateAdapter);
    else
        listView.setAdapter(adapter);

    // Finalize arrays to prepare for handling clicked items
    final String[] finalListByDate = listOfNotesByDate;
    final String[] finalListByName = listOfNotesByName;

    // Make ListView handle clicked items
    listView.setClickable(true);
    listView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
            if (sortBy.equals("date")) {
                if (directEdit)
                    listener.editNote(finalListByDate[position]);
                else
                    listener.viewNote(finalListByDate[position]);
            } else if (sortBy.equals("name")) {
                if (directEdit)
                    listener.editNote(finalListByName[position]);
                else
                    listener.viewNote(finalListByName[position]);
            }
        }
    });

    // Make ListView handle contextual action bar
    final ArrayList<String> cab = new ArrayList<>(numOfNotes);

    listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
    listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            // Respond to clicks on the actions in the CAB
            switch (item.getItemId()) {
            case R.id.action_export:
                mode.finish(); // Action picked, so close the CAB
                listener.exportNote(cab.toArray());
                return true;
            case R.id.action_delete:
                mode.finish(); // Action picked, so close the CAB
                listener.deleteNote(cab.toArray());
                return true;
            default:
                return false;
            }
        }

        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            listener.hideFab();

            // Inflate the menu for the CAB
            MenuInflater inflater = mode.getMenuInflater();
            inflater.inflate(R.menu.context_menu, menu);

            // Clear any old values from cab array
            cab.clear();

            return true;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            listener.showFab();
        }

        @Override
        public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
            // Add/remove filenames to cab array as they are checked/unchecked
            if (checked) {
                if (sortBy.equals("date"))
                    cab.add(finalListByDate[position]);
                if (sortBy.equals("name"))
                    cab.add(finalListByName[position]);
            } else {
                if (sortBy.equals("date"))
                    cab.remove(finalListByDate[position]);
                if (sortBy.equals("name"))
                    cab.remove(finalListByName[position]);
            }

            // Update the title in CAB
            if (cab.size() == 0)
                mode.setTitle("");
            else
                mode.setTitle(cab.size() + " " + listener.getCabString(cab.size()));
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }
    });

    // If there are no saved notes, then display the empty view
    if (numOfNotes == 0) {
        TextView empty = (TextView) getActivity().findViewById(R.id.empty);
        listView.setEmptyView(empty);
    }
}

From source file:tw.idv.palatis.danboorugallery.PostListActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // enable progress icon
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setProgressBarIndeterminate(true);// w w w  .  ja  va 2s  .  c  o  m

    setContentView(R.layout.activity_post_list);

    // enable ActionBar app icon to behave as action to toggle nav drawer
    getActionBar().setDisplayHomeAsUpEnabled(true);
    getActionBar().setHomeButtonEnabled(true);

    // setup drawer
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerLeft = (RelativeLayout) findViewById(R.id.left_drawer);
    mDrawerRight = (RelativeLayout) findViewById(R.id.right_drawer);
    ListView hostsList = (ListView) findViewById(R.id.host_list);
    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open,
            R.string.drawer_close) {
        @Override
        public void onDrawerStateChanged(int newState) {
            super.onDrawerStateChanged(newState);

            if (newState == DrawerLayout.STATE_DRAGGING)
                mUiHider.show();
        }

        @Override
        public void onDrawerSlide(View drawerView, float slideOffset) {
            super.onDrawerSlide(drawerView, slideOffset);
        }

        public void onDrawerClosed(View view) {
            if (!mIsDoingSearch && !mDrawerLayout.isDrawerVisible(mDrawerLeft)
                    && !mDrawerLayout.isDrawerVisible(mDrawerRight)) {
                mUiHider.setAutoHideDelay(AUTO_HIDE_DELAY_MILLIS);
                mUiHider.hide();
            }
        }

        public void onDrawerOpened(View drawerView) {
            mUiHider.setAutoHideDelay(UiHider.AUTO_HIDE_DELAY_DISABLED);
            mUiHider.show();
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    HostsTable.registerDataSetObserver(new DataSetObserver() {
        @Override
        public void onChanged() {
            super.onChanged();
            getLoaderManager().restartLoader(R.id.loader_host_ids, null, PostListActivity.this);
        }

        @Override
        public void onInvalidated() {
            super.onInvalidated();
            mHostsAdapter.swapCursor(null);
        }
    });
    mHostsAdapter = new CursorAdapter(this, null, false) {
        private CompoundButton.OnCheckedChangeListener mOnCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton button, boolean checked) {
                ViewHolder holder = (ViewHolder) button.getTag(R.id.view_tag_view_holder);
                Host host = SiteSession.getHostById(holder.host_id);
                host.enabled = checked;
                HostsTable.addOrUpdateHost(host);
            }
        };

        class ViewHolder {
            int host_id;
            TextView title;
            TextView summary;
            CheckBox toggle;

            public ViewHolder(View view, int host_id) {
                this.host_id = host_id;
                this.title = (TextView) view.findViewById(android.R.id.title);
                this.summary = (TextView) view.findViewById(android.R.id.summary);
                this.toggle = (CheckBox) view.findViewById(android.R.id.toggle);
                this.toggle.setTag(R.id.view_tag_view_holder, this);
            }
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
            View view = inflater.inflate(R.layout.listitem_drawer_host_item, parent, false);
            view.setTag(R.id.view_tag_view_holder,
                    new ViewHolder(view, cursor.getInt(HostsTable.INDEX_HOST_DATABASE_ID)));
            return view;
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            Host host = SiteSession.getHostById(cursor.getInt(HostsTable.INDEX_HOST_DATABASE_ID));
            if (host == null)
                return;

            ViewHolder holder = (ViewHolder) view.getTag(R.id.view_tag_view_holder);

            holder.host_id = host.id;
            holder.toggle.setChecked(host.enabled);
            holder.title.setText(host.name);
            holder.summary.setText(host.url);
            holder.toggle.setOnCheckedChangeListener(mOnCheckedChangeListener);
        }
    };
    DrawerListAdapter adapter = new DrawerListAdapter(this, mHostsAdapter);
    hostsList.setAdapter(adapter);
    hostsList.setChoiceMode(AbsListView.CHOICE_MODE_NONE);
    hostsList.setOnItemClickListener(this);
    hostsList.setOnItemLongClickListener(this);

    getLoaderManager().initLoader(R.id.loader_host_ids, null, this);

    // Set up an instance of SystemUiHider to control the system UI for
    // this activity.
    mUiHider = new UiHider(AUTO_HIDE_DELAY_MILLIS, new UiHider.OnVisibilityChangeListener() {
        @Override
        public void onVisibilityChange(boolean visible) {
            if (visible)
                getActionBar().show();
            else
                getActionBar().hide();
        }
    });

    if (savedInstanceState == null) {
        mPostListFragment = new PostListFragment();
        getFragmentManager().beginTransaction().replace(R.id.post_list_container, mPostListFragment).commit();
    }
}

From source file:com.anjalimacwan.fragment.NoteListFragment.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void listNotes() {
    // Get number of files
    int numOfFiles = getNumOfNotes(getActivity().getFilesDir());
    int numOfNotes = numOfFiles;

    // Get array of file names
    String[] listOfFiles = getListOfNotes(getActivity().getFilesDir());
    ArrayList<String> listOfNotes = new ArrayList<>();

    // Remove any files from the list that aren't notes
    for (int i = 0; i < numOfFiles; i++) {
        if (NumberUtils.isNumber(listOfFiles[i]))
            listOfNotes.add(listOfFiles[i]);
        else//w w w.  j a v a  2  s . co m
            numOfNotes--;
    }

    // Declare ListView
    final ListView listView = (ListView) getActivity().findViewById(R.id.listView1);

    // Create arrays of note lists
    String[] listOfNotesByDate = new String[numOfNotes];
    String[] listOfNotesByName = new String[numOfNotes];

    NoteListItem[] listOfTitlesByDate = new NoteListItem[numOfNotes];
    NoteListItem[] listOfTitlesByName = new NoteListItem[numOfNotes];

    ArrayList<NoteListItem> list = new ArrayList<>(numOfNotes);

    for (int i = 0; i < numOfNotes; i++) {
        listOfNotesByDate[i] = listOfNotes.get(i);
    }

    // If sort-by is "by date", sort in reverse order
    if (sortBy.equals("date"))
        Arrays.sort(listOfNotesByDate, Collections.reverseOrder());

    // Get array of first lines of each note
    for (int i = 0; i < numOfNotes; i++) {
        try {
            String title = listener.loadNoteTitle(listOfNotesByDate[i]);
            String date = listener.loadNoteDate(listOfNotesByDate[i]);
            listOfTitlesByDate[i] = new NoteListItem(title, date);
        } catch (IOException e) {
            showToast(R.string.error_loading_list);
        }
    }

    // If sort-by is "by name", sort alphabetically
    if (sortBy.equals("name")) {
        // Copy titles array
        System.arraycopy(listOfTitlesByDate, 0, listOfTitlesByName, 0, numOfNotes);

        // Sort titles
        Arrays.sort(listOfTitlesByName, NoteListItem.NoteComparatorTitle);

        // Initialize notes array
        for (int i = 0; i < numOfNotes; i++)
            listOfNotesByName[i] = "new";

        // Copy filenames array with new sort order of titles and nullify date arrays
        for (int i = 0; i < numOfNotes; i++) {
            for (int j = 0; j < numOfNotes; j++) {
                if (listOfTitlesByName[i].getNote().equals(listOfTitlesByDate[j].getNote())
                        && listOfNotesByName[i].equals("new")) {
                    listOfNotesByName[i] = listOfNotesByDate[j];
                    listOfNotesByDate[j] = "";
                    listOfTitlesByDate[j] = new NoteListItem("", "");
                }
            }
        }

        // Populate ArrayList with notes, showing name as first line of the notes
        list.addAll(Arrays.asList(listOfTitlesByName));
    } else if (sortBy.equals("date"))
        list.addAll(Arrays.asList(listOfTitlesByDate));

    // Create the custom adapters to bind the array to the ListView
    final NoteListDateAdapter dateAdapter = new NoteListDateAdapter(getActivity(), list);
    final NoteListAdapter adapter = new NoteListAdapter(getActivity(), list);

    // Display the ListView
    if (showDate)
        listView.setAdapter(dateAdapter);
    else
        listView.setAdapter(adapter);

    // Finalize arrays to prepare for handling clicked items
    final String[] finalListByDate = listOfNotesByDate;
    final String[] finalListByName = listOfNotesByName;

    // Make ListView handle clicked items
    listView.setClickable(true);
    listView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
            if (sortBy.equals("date")) {
                if (directEdit)
                    listener.editNote(finalListByDate[position]);
                else
                    listener.viewNote(finalListByDate[position]);
            } else if (sortBy.equals("name")) {
                if (directEdit)
                    listener.editNote(finalListByName[position]);
                else
                    listener.viewNote(finalListByName[position]);
            }
        }
    });

    // Make ListView handle contextual action bar
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        final ArrayList<String> cab = new ArrayList<>(numOfNotes);

        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
        listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {

            @Override
            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                // Respond to clicks on the actions in the CAB
                switch (item.getItemId()) {
                case R.id.action_export:
                    mode.finish(); // Action picked, so close the CAB
                    listener.exportNote(cab.toArray());
                    return true;
                case R.id.action_delete:
                    mode.finish(); // Action picked, so close the CAB
                    listener.deleteNote(cab.toArray());
                    return true;
                default:
                    return false;
                }
            }

            @Override
            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                listener.hideFab();

                // Inflate the menu for the CAB
                MenuInflater inflater = mode.getMenuInflater();
                inflater.inflate(R.menu.context_menu, menu);

                // Clear any old values from cab array
                cab.clear();

                return true;
            }

            @Override
            public void onDestroyActionMode(ActionMode mode) {
                listener.showFab();
            }

            @Override
            public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
                // Add/remove filenames to cab array as they are checked/unchecked
                if (checked) {
                    if (sortBy.equals("date"))
                        cab.add(finalListByDate[position]);
                    if (sortBy.equals("name"))
                        cab.add(finalListByName[position]);
                } else {
                    if (sortBy.equals("date"))
                        cab.remove(finalListByDate[position]);
                    if (sortBy.equals("name"))
                        cab.remove(finalListByName[position]);
                }

                // Update the title in CAB
                if (cab.size() == 0)
                    mode.setTitle("");
                else
                    mode.setTitle(cab.size() + " " + listener.getCabString(cab.size()));
            }

            @Override
            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                return false;
            }
        });
    }

    // If there are no saved notes, then display the empty view
    if (numOfNotes == 0) {
        TextView empty = (TextView) getActivity().findViewById(R.id.empty);
        listView.setEmptyView(empty);
    }
}

From source file:net.kazzz.NFCTagWriter.java

/**
 * ISO15693 Tag????????/*www  .  j a  v  a 2 s.  c om*/
 * 
 * 
 * @param btnWrite ?????
 * @param editWrite ??
 * @param listMemBlock?
 * @param useNDEFNDEF????
 */
private void prepareISO15693(final Button btnWrite, final EditText editWrite, final ListView listMemBlock) {
    final CheckBox chkUseNDEF = (CheckBox) findViewById(R.id.chk_useNDEF);

    //??
    ISO15693Tag ft = new ISO15693Tag(this.mNfcTag);
    try {
        SystemInformationResponse sysInfo = ft.getSystemInformation();
        if (sysInfo == null || sysInfo.hasError()) {
            throw new ISO15693Exception(
                    "ISO15693 ??????????? : "
                            + sysInfo.getErrorCode());
        }

        final MemorySizeInfo memInfo = sysInfo.getMemoryInfo();
        if (memInfo == null || memInfo.getNumberOfBlocks() == 0) {
            throw new ISO15693Exception("ISO15693 ?????????");
        }

        chkUseNDEF.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                listMemBlock.setEnabled(!chkUseNDEF.isChecked());
                listMemBlock.setClickable(!chkUseNDEF.isChecked());
                //NDEF??NDEF?????
                if (chkUseNDEF.isChecked()) {
                    btnWrite.setEnabled(true);
                    editWrite.setEnabled(true);
                    //NDEF????10byte?
                    editWrite.setHint((memInfo.getBlockSize() * memInfo.getNumberOfBlocks()) - 10
                            + "??");
                } else {
                    if (editWrite.getText().length() > 0) {
                        btnWrite.setEnabled(true);
                        editWrite.setEnabled(true);
                    } else {
                        btnWrite.setEnabled(false);
                        editWrite.setEnabled(false);
                    }
                    editWrite.setHint(memInfo.getBlockSize() + "??");
                }
            }
        });

        ReadMultipleBlocksResponse rbResp = ft.readMultipleBlocks((byte) 0, memInfo.getBlockSize(),
                memInfo.getNumberOfBlocks());
        if (rbResp == null || rbResp.hasError()) {
            throw new ISO15693Exception(
                    "ISO15693 ReadMultipleBlock?????" + sysInfo.getErrorCode());
        }

        //??????
        ViewHolder[] holders = new ViewHolder[memInfo.getNumberOfBlocks()];
        for (byte i = 0; i < memInfo.getNumberOfBlocks(); i++) {
            BlockData bd = rbResp.getBlockDatas()[i];

            ViewHolder holder = new ViewHolder();
            holder.blockName = "block " + i;
            holder.isWritable = !bd.isLocked();
            holder.accessMode = bd.isLocked() ? "(Lock)" : "(UnLock)";

            //??
            if (bd.getData() != null && bd.getData().length > 0) {
                holder.data = bd.getData();
            } else {
                holder.data = new byte[memInfo.getBlockSize()];
                for (int b = 0; b < holder.data.length; b++) {
                    holder.data[b] = 0x00; //??
                }
            }
            holders[i] = holder;
        }
        final LayoutInflater layoutInflater = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        //ArrayAdapter? (??
        ArrayAdapter<ViewHolder> adapter = new ArrayAdapter<ViewHolder>(this,
                android.R.layout.simple_list_item_multiple_choice, holders) {

            /* (non-Javadoc)
             * @see android.widget.BaseAdapter#isEnabled(int)
             */
            @Override
            public boolean isEnabled(int position) {
                SparseBooleanArray arry = listMemBlock.getCheckedItemPositions();
                if (arry.indexOfValue(true) != -1 && !arry.get(position) //??????? 
                        && (!arry.get(position - 1) && !arry.get(position + 1))) //????? 
                {
                    //???????
                    return false;
                }
                return super.isEnabled(position);
            }

            /* (non-Javadoc)
             * @see android.widget.ArrayAdapter#getView(int, android.view.View, android.view.ViewGroup)
             */
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {

                if (null == convertView) {
                    convertView = layoutInflater.inflate(android.R.layout.simple_list_item_multiple_choice,
                            null);
                }

                ViewHolder holder = this.getItem(position);

                if (holder != null) {

                    StringBuilder sb = new StringBuilder();
                    sb.append(holder.blockName).append(" ").append(holder.accessMode).append("\n");
                    if (holder.data != null && holder.data.length > 0) {
                        //UTF-8?
                        Charset utfEncoding = Charset.forName("UTF-8");
                        sb.append(" : ").append(new String(holder.data, utfEncoding).trim());
                    }
                    ((TextView) convertView).setText(sb.toString());
                }
                return convertView;
            }

        };

        listMemBlock.setAdapter(adapter);

        // ?????  
        //listMemBlock.setItemsCanFocus(false);  
        //?
        listMemBlock.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

        listMemBlock.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                //?????
                SparseBooleanArray arry = listMemBlock.getCheckedItemPositions();

                ByteBuffer buff = ByteBuffer.allocate(arry.size() * memInfo.getBlockSize());
                int writableBlockCount = 0;
                for (int i = 0; i < arry.size(); i++) {
                    int key = arry.keyAt(i);
                    //?????
                    Object o = parent.getItemAtPosition(key);
                    if (o != null && o instanceof ViewHolder) {
                        ViewHolder holder = (ViewHolder) o;
                        if (holder.isWritable) {
                            writableBlockCount++;
                            if (holder.data != null && holder.data.length > 0) {
                                buff.put(holder.data);
                            }
                        }
                    }
                }
                //UTF-8?
                StringBuilder sb = new StringBuilder();
                Charset utfEncoding = Charset.forName("UTF-8");
                sb.append(new String(buff.array(), utfEncoding).trim());

                editWrite.setHint(memInfo.getBlockSize() * writableBlockCount + "??");

                if (writableBlockCount > 0) {
                    editWrite.setText(sb.toString().trim());
                    editWrite.setTag(arry);
                    //????????????
                    btnWrite.setEnabled(true);
                    editWrite.setEnabled(true);
                } else {
                    btnWrite.setEnabled(false);
                    editWrite.setEnabled(false);
                }

            }
        });
    } catch (ISO15693Exception e) {
        e.printStackTrace();
        Log.e(TAG, e.toString());
    }
}