Example usage for android.view View inflate

List of usage examples for android.view View inflate

Introduction

In this page you can find the example usage for android.view View inflate.

Prototype

public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) 

Source Link

Document

Inflate a view from an XML resource.

Usage

From source file:ca.appvelopers.mcgillmobile.ui.ScheduleActivity.java

/**
 * Shows a dialog with course information
 *
 * @param course Clicked course/* ww  w.  ja va  2s. co m*/
 */
public void showCourseDialog(final Course course) {
    analytics.sendScreen("Schedule - Course");

    //Inflate the body
    View layout = View.inflate(this, R.layout.dialog_course, null);

    //Title
    TextView title = (TextView) layout.findViewById(R.id.course_title);
    title.setText(course.getTitle());

    //Time
    TextView time = (TextView) layout.findViewById(R.id.course_time);
    time.setText(course.getTimeString());

    //Location
    TextView location = (TextView) layout.findViewById(R.id.course_location);
    location.setText(course.getLocation());

    //Type
    TextView type = (TextView) layout.findViewById(R.id.course_type);
    type.setText(course.getType());

    //Instructor
    TextView instructor = (TextView) layout.findViewById(R.id.course_instructor);
    instructor.setText(course.getInstructor());

    //Section
    TextView section = (TextView) layout.findViewById(R.id.course_section);
    section.setText(course.getSection());

    //Credits
    TextView credits = (TextView) layout.findViewById(R.id.course_credits);
    credits.setText(String.valueOf(course.getCredits()));

    //CRN
    TextView crn = (TextView) layout.findViewById(R.id.course_crn);
    crn.setText(String.valueOf(course.getCRN()));

    //Docuum Link
    TextView docuum = (TextView) layout.findViewById(R.id.course_docuum);
    docuum.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Utils.openURL(ScheduleActivity.this, "http://www.docuum.com/mcgill/"
                    + course.getSubject().toLowerCase() + "/" + course.getNumber());
        }
    });

    //Show on Map
    TextView map = (TextView) layout.findViewById(R.id.course_map);
    map.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //TODO
        }
    });

    new AlertDialog.Builder(this).setTitle(course.getCode()).setView(layout).setCancelable(true)
            .setNeutralButton(R.string.done, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).show();
}

From source file:com.uzmap.pkg.uzmodules.UISearchBar.SearchBarActivity.java

@SuppressWarnings("deprecation")
private void initData() {

    DisplayMetrics metric = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metric);
    mPref = getSharedPreferences("text", Context.MODE_PRIVATE);
    String text = mPref.getString("text", "");
    if (!TextUtils.isEmpty(text)) {
        mEditText.setText(text);/*ww w.j a  va2 s.c  o m*/
        mEditText.setSelection(text.length());
    }

    mNavigationLayout.setBackgroundColor(config.navBgColor);

    if (TextUtils.isEmpty(config.searchBoxBgImg)) {
        BitmapDrawable bitmapDrawable = new BitmapDrawable(BitmapFactory.decodeResource(getResources(),
                UZResourcesIDFinder.getResDrawableID("mo_searchbar_bg")));
        mRelativeLayout.setBackgroundDrawable(bitmapDrawable);
    } else {
        BitmapDrawable bitmapDrawable = new BitmapDrawable(generateBitmap(config.searchBoxBgImg));
        mRelativeLayout.setBackgroundDrawable(bitmapDrawable);
    }

    if (config.cancel_bg_bitmap != null) {
        mTextView.setBackgroundDrawable(new BitmapDrawable(config.cancel_bg_bitmap));
    } else {
        mTextView.setBackgroundColor(config.cancel_bg_color);
    }

    mTextView.setTextSize(config.cancel_size);
    mTextView.setTextColor(config.cancal_color);

    LayoutParams params = new LayoutParams(UZUtility.dipToPix(config.searchBoxWidth),
            UZUtility.dipToPix(config.searchBoxHeight));
    params.setMargins(UZUtility.dipToPix(10), 0, 0, 0);

    params.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
    mEditText.setLayoutParams(params);

    WindowManager wm = this.getWindowManager();
    int width = wm.getDefaultDisplay().getWidth();

    double realWidth = width * 0.80;
    LayoutParams layoutParams = new LayoutParams((int) realWidth, UZUtility.dipToPix(config.searchBoxHeight));

    layoutParams.setMargins(UZUtility.dipToPix(5), 0, 0, 0);
    layoutParams.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);

    layoutParams.topMargin = UZUtility.dipToPix(8);
    layoutParams.bottomMargin = UZUtility.dipToPix(8);

    mRelativeLayout.setLayoutParams(layoutParams);

    double cancelRealWidth = width * 0.15;

    int space = (width - (int) realWidth - (int) cancelRealWidth - UZUtility.dipToPix(5)) / 2;

    LayoutParams cancalTxtParam = new LayoutParams((int) cancelRealWidth,
            UZUtility.dipToPix(config.searchBoxHeight));

    cancalTxtParam.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
    cancalTxtParam.addRule(RelativeLayout.CENTER_VERTICAL);

    cancalTxtParam.rightMargin = space;
    cancalTxtParam.leftMargin = space;

    mTextView.setLayoutParams(cancalTxtParam);

    mListView.setBackgroundColor(config.list_bg_color);

    listSize = config.list_size;
    mCleanTextColor = config.clear_font_color;
    mCleanTextSize = config.clear_font_size;

    recordCount = config.historyCount;

    /**
     * add clean list item
     */
    int relativeLayoutCleanId = UZResourcesIDFinder.getResLayoutID("mo_searchbar_clean_item");
    relativeLayoutClean = (LinearLayout) View.inflate(getApplicationContext(), relativeLayoutCleanId, null);
    int tv_cleanId = UZResourcesIDFinder.getResIdID("tv_clean");
    mCleanTV = (TextView) relativeLayoutClean.findViewById(tv_cleanId);
    mCleanTV.setTextSize(mCleanTextSize);
    mCleanTV.setTextColor(mCleanTextColor);

    mCleanTV.setText(config.clearText);

    relativeLayoutClean
            .setBackgroundDrawable(addStateDrawable(config.clear_bg_color, config.clear_active_bg_color));
    list.clear();

    list.add(relativeLayoutClean);
    mPref = getSharedPreferences("history" + config.database, Context.MODE_PRIVATE);

    editor = mPref.edit();

    trimHistroyList(config.historyCount);

    @SuppressWarnings("unchecked")
    Map<String, String> map = (Map<String, String>) mPref.getAll();
    if (map != null) {
        if (map.size() != 0) {
            for (int i = 1; i <= map.size(); i++) {

                int listview_item = UZResourcesIDFinder.getResLayoutID("mo_searchbar_listview_item");
                LinearLayout linearLayout = (LinearLayout) View.inflate(SearchBarActivity.this, listview_item,
                        null);
                int tv_listId = UZResourcesIDFinder.getResIdID("tv_listview");
                TextView tv = (TextView) linearLayout.findViewById(tv_listId);
                tv.setTextSize(listSize);
                tv.setTextColor(config.list_color);

                linearLayout.setBackgroundDrawable(
                        addStateDrawable(config.list_bg_color, config.list_item_active_bg_color));

                int itemBorderLineId = UZResourcesIDFinder.getResIdID("item_border_line");
                linearLayout.findViewById(itemBorderLineId).setBackgroundColor(config.list_border_color);

                for (Entry<String, String> iterable_element : map.entrySet()) {
                    String key = iterable_element.getKey();
                    if ((i + "").equals(key)) {
                        tv.setText(iterable_element.getValue());
                    }
                }
                list.addFirst(linearLayout);
            }
            id = map.size();
        }
    }

    adapter = new MyAdapter();
    mListView.setAdapter(adapter);
}

From source file:com.money.manager.ex.common.AllDataListFragment.java

private void renderFooter() {
    this.footer = (LinearLayout) View.inflate(getActivity(), R.layout.item_generic_report_2_columns, null);

    TextView txtColumn1 = (TextView) footer.findViewById(R.id.textViewColumn1);
    TextView txtColumn2 = (TextView) footer.findViewById(R.id.textViewColumn2);

    txtColumn1.setText(R.string.total);/*  w w  w  . j av  a 2s .c  o  m*/
    txtColumn1.setTypeface(null, Typeface.BOLD_ITALIC);
    txtColumn2.setText(R.string.total);
    txtColumn2.setTypeface(null, Typeface.BOLD_ITALIC);

    ListView listView = getListView();
    listView.addFooterView(footer);
}

From source file:com.doplgangr.secrecy.views.FilesListFragment.java

void createFolder() {
    final View dialogView = View.inflate(context, R.layout.add_folder, null);
    new AlertDialog.Builder(context).setTitle(getString(R.string.Vault__create_new_folder)).setView(dialogView)
            .setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    String newFolderName = ((EditText) dialogView.findViewById(R.id.folderName)).getText()
                            .toString();

                    Util.log("Create folder " + newFolderName);
                }/*w  ww  . j  a  v  a2 s  .  co m*/
            }).setNegativeButton(R.string.CANCEL, Util.emptyClickListener).show();
}

From source file:com.sonymobile.androidapp.gridcomputing.activities.SummaryActivity.java

/**
 * Setup the not met conditions pager./* www  .  ja v  a  2 s .c  o m*/
 * @param message the message fired when the conditions changes.
 */
private void setupConditionsLayout(final ConditionMessage message) {
    final boolean charger = !message.getNotMetConditions().contains(ConditionType.CHARGER);
    final boolean battery = !message.getNotMetConditions().contains(ConditionType.BATTERY);
    final boolean wifi = !message.getNotMetConditions().contains(ConditionType.WIFI);
    final boolean allConditionsMet = charger && battery && wifi;
    if (allConditionsMet) {
        mConditionsLayout.setVisibility(View.INVISIBLE);
        mBackgroundImage.setAlpha(1F);
    } else {
        mConditionsLayout.setVisibility(View.VISIBLE);
        mBackgroundImage.setAlpha(BACKGROUND_IMAGE_ALPHA);

        if (mAdapter == null) {
            mAdapter = new ConditionsSlidePagerAdapter(getSupportFragmentManager());
            mConditionsViewPager.setAdapter(mAdapter);

            mConditionsViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(final int position, final float positionOffset,
                        final int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(final int position) {
                    //updates the indicator selection
                    for (int i = 0; i < mConditionsIndicator.getChildCount(); i++) {
                        mConditionsIndicator.getChildAt(i).setSelected(i == position);
                    }
                }

                @Override
                public void onPageScrollStateChanged(final int state) {

                }
            });
        }

        // Creates a new list because we're only interested in 3 conditions:
        // charger, battery, wifi.
        final List<ConditionType> notMetList = new ArrayList<>();
        if (!charger) {
            notMetList.add(ConditionType.CHARGER);
        }
        if (!battery) {
            notMetList.add(ConditionType.BATTERY);
        }
        if (!wifi) {
            notMetList.add(ConditionType.WIFI);
        }
        mAdapter.setConditionsNotMetList(notMetList);

        //adding the indicators and selecting the first one
        mConditionsIndicator.removeAllViews();
        if (notMetList.size() > 1) {
            for (int i = 0; i < notMetList.size(); i++) {
                View.inflate(this, R.layout.view_pager_indicator, mConditionsIndicator);
            }
            mConditionsIndicator.getChildAt(0).setSelected(true);
        }
    }
}

From source file:cs.umass.edu.prepare.view.activities.CalendarActivity.java

/**
 * Populates the details view with adherence data for a particular date.
 * @param dateKey corresponds to the selected date. Note that the date key must have zeroed
 *                out all fields excluding month, year and date.
 * @param insertPoint the parent to which the adherence views are to be added.
 *//*from w w  w. j  a  v a  2 s  . c  o m*/
private void insertDetailsForDate(final Calendar dateKey, ViewGroup insertPoint) {
    final Map<Medication, Adherence[]> adherenceMap = adherenceData.get(dateKey);
    for (final Medication medication : medications) {
        View details = View.inflate(this, R.layout.view_adherence_details_full, null);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

        View[] adherenceViews = new View[2];
        int[] viewIDs = new int[] { R.id.adherence_details1, R.id.adherence_details2 };
        int[] timeTakenIDs = new int[] { R.id.txtTimeTaken1, R.id.txtTimeTaken2 };
        int[] medicationImgIDs = new int[] { R.id.imgMedication1, R.id.imgMedication2 };
        final Adherence[] adherence = adherenceMap.get(medication);
        int dosage = dosageMapping.get(medication);
        Calendar[] schedule = dailySchedule.get(medication);

        for (int i = 0; i < viewIDs.length; i++) {
            final int index = i;
            adherenceViews[index] = details.findViewById(viewIDs[index]);
            // TODO : Swiping on details doesn't work as expected (only works for adherence view):
            //            motionEventListener.setOnSwipeListener(adherenceViews[index], onDetailsSwiped);
            adherenceViews[index].setOnLongClickListener(view -> {
                editAdherence(medication, dateKey, index);
                return false;
            });
            adherenceViews[index].setOnClickListener(view -> {
                if (adherence[index].getAdherenceType() == Adherence.AdherenceType.TAKEN_CLARIFY_TIME) {
                    setTimeTaken(medication, dateKey, index);
                }
            });
            adherenceViews[index]
                    .setBackground(Utils.getDrawableForAdherence(this, adherence[index].getAdherenceType()));
            TextView timeTaken = (TextView) details.findViewById(timeTakenIDs[index]);
            TextView imgMedication = (TextView) details.findViewById(medicationImgIDs[index]);
            BitmapDrawable medicationDrawable = new BitmapDrawable(getResources(), medication.getImage());
            imgMedication.setCompoundDrawablesWithIntrinsicBounds(null, medicationDrawable, null, null);
            imgMedication.setText(String.format(Locale.getDefault(), "%d mg", dosage));
            adherenceViews[index].setVisibility(View.VISIBLE);
            switch (adherence[index].getAdherenceType()) {
            case NONE:
                adherenceViews[index].setVisibility(View.INVISIBLE);
                break;
            case MISSED:
                timeTaken.setText(R.string.adherence_text_missed);
                break;
            case TAKEN_CLARIFY_TIME:
                timeTaken.setText(R.string.adherence_text_unknown);
                break;
            case FUTURE:
                timeTaken.setText(timeFormat.format(schedule[index].getTime()));
                break;
            default: // taken on-time or taken late/early
                Calendar time = adherence[index].getTimeTaken();
                if (time != null)
                    timeTaken.setText(timeFormat.format(time.getTime()));
                break;
            }
        }
        // set margins and add to parent
        layoutParams.setMargins(0, 15, 0, 15);
        insertPoint.addView(details, layoutParams);
    }
}

From source file:com.easemob.chatuidemo.activity.BaseChatActivity.java

/**
 * ?gridview?view/*from w w w  . ja va 2s. co m*/
 *
 * @param i
 * @return
 */
private View getGridChildView(int i) {
    View view = View.inflate(this, R.layout.expression_gridview, null);
    ExpandGridView gv = (ExpandGridView) view.findViewById(R.id.gridview);
    List<String> list = new ArrayList<String>();
    if (i == 1) {
        List<String> list1 = reslist.subList(0, 20);
        list.addAll(list1);
    } else if (i == 2) {
        list.addAll(reslist.subList(20, reslist.size()));
    }
    list.add("delete_expression");
    final ExpressionAdapter expressionAdapter = new ExpressionAdapter(this, 1, list);
    gv.setAdapter(expressionAdapter);
    gv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String filename = expressionAdapter.getItem(position);
            try {
                // ????
                // ?????
                //                    if (buttonSetModeKeyboard.getVisibility() != View.VISIBLE) {
                if (filename != "delete_expression") { // ?
                    // ????SmileUtils
                    Class clz = Class.forName("com.easemob.chatuidemo.utils.SmileUtils");
                    Field field = clz.getField(filename);
                    mEditTextContent
                            .append(SmileUtils.getSmiledText(BaseChatActivity.this, (String) field.get(null)));
                } else { // 
                    if (!TextUtils.isEmpty(mEditTextContent.getText())) {

                        int selectionStart = mEditTextContent.getSelectionStart();// ??
                        if (selectionStart > 0) {
                            String body = mEditTextContent.getText().toString();
                            String tempStr = body.substring(0, selectionStart);
                            int i = tempStr.lastIndexOf("[");// ???
                            if (i != -1) {
                                CharSequence cs = tempStr.substring(i, selectionStart);
                                if (SmileUtils.containsKey(cs.toString()))
                                    mEditTextContent.getEditableText().delete(i, selectionStart);
                                else
                                    mEditTextContent.getEditableText().delete(selectionStart - 1,
                                            selectionStart);
                            } else {
                                mEditTextContent.getEditableText().delete(selectionStart - 1, selectionStart);
                            }
                        }
                    }

                    //                        }
                }
            } catch (Exception e) {
            }

        }
    });
    return view;
}

From source file:de.baumann.browser.helper.helper_main.java

public static void openFilePicker(final Activity activity, final View view, final String startDir) {

    new ChooserDialog().with(activity).withStartFile(startDir).withChosenListener(new ChooserDialog.Result() {
        @Override/*from  www. jav  a 2s . c o  m*/
        public void onChoosePath(final File pathFile) {

            final String fileExtension = pathFile.getAbsolutePath()
                    .substring(pathFile.getAbsolutePath().lastIndexOf("."));
            final String fileName = pathFile.getAbsolutePath()
                    .substring(pathFile.getAbsolutePath().lastIndexOf("/") + 1);
            final String fileNameWE = fileName.substring(0, fileName.lastIndexOf("."));

            final CharSequence[] options = { activity.getString(R.string.choose_menu_1),
                    activity.getString(R.string.choose_menu_2), activity.getString(R.string.choose_menu_3),
                    activity.getString(R.string.choose_menu_4) };

            final AlertDialog.Builder dialog = new AlertDialog.Builder(activity);
            dialog.setPositiveButton(R.string.toast_cancel, new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int whichButton) {
                    dialog.cancel();
                }
            });
            dialog.setItems(options, new DialogInterface.OnClickListener() {
                @SuppressWarnings("ResultOfMethodCallIgnored")
                @Override
                public void onClick(DialogInterface dialog, int item) {
                    if (options[item].equals(activity.getString(R.string.choose_menu_1))) {

                        String text = (activity.getString(R.string.toast_extension) + ": " + fileExtension);

                        switch (fileExtension) {
                        case ".gif":
                        case ".bmp":
                        case ".tiff":
                        case ".svg":
                        case ".png":
                        case ".jpg":
                        case ".jpeg":
                            helper_main.openFile(activity, pathFile, "image/*", view);
                            break;
                        case ".m3u8":
                        case ".mp3":
                        case ".wma":
                        case ".midi":
                        case ".wav":
                        case ".aac":
                        case ".aif":
                        case ".amp3":
                        case ".weba":
                            helper_main.openFile(activity, pathFile, "audio/*", view);
                            break;
                        case ".mpeg":
                        case ".mp4":
                        case ".ogg":
                        case ".webm":
                        case ".qt":
                        case ".3gp":
                        case ".3g2":
                        case ".avi":
                        case ".f4v":
                        case ".flv":
                        case ".h261":
                        case ".h263":
                        case ".h264":
                        case ".asf":
                        case ".wmv":
                            helper_main.openFile(activity, pathFile, "video/*", view);
                            break;
                        case ".rtx":
                        case ".csv":
                        case ".txt":
                        case ".vcs":
                        case ".vcf":
                        case ".css":
                        case ".ics":
                        case ".conf":
                        case ".config":
                        case ".java":
                            helper_main.openFile(activity, pathFile, "text/*", view);
                            break;
                        case ".html":
                            helper_main.openFile(activity, pathFile, "text/html", view);
                            break;
                        case ".apk":
                            helper_main.openFile(activity, pathFile, "application/vnd.android.package-archive",
                                    view);
                            break;
                        case ".pdf":
                            helper_main.openFile(activity, pathFile, "application/pdf", view);
                            break;
                        case ".doc":
                            helper_main.openFile(activity, pathFile, "application/msword", view);
                            break;
                        case ".xls":
                            helper_main.openFile(activity, pathFile, "application/vnd.ms-excel", view);
                            break;
                        case ".ppt":
                            helper_main.openFile(activity, pathFile, "application/vnd.ms-powerpoint", view);
                            break;
                        case ".docx":
                            helper_main.openFile(activity, pathFile,
                                    "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                                    view);
                            break;
                        case ".pptx":
                            helper_main.openFile(activity, pathFile,
                                    "application/vnd.openxmlformats-officedocument.presentationml.presentation",
                                    view);
                            break;
                        case ".xlsx":
                            helper_main.openFile(activity, pathFile,
                                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", view);
                            break;
                        case ".odt":
                            helper_main.openFile(activity, pathFile, "application/vnd.oasis.opendocument.text",
                                    view);
                            break;
                        case ".ods":
                            helper_main.openFile(activity, pathFile,
                                    "application/vnd.oasis.opendocument.spreadsheet", view);
                            break;
                        case ".odp":
                            helper_main.openFile(activity, pathFile,
                                    "application/vnd.oasis.opendocument.presentation", view);
                            break;
                        case ".zip":
                            helper_main.openFile(activity, pathFile, "application/zip", view);
                            break;
                        case ".rar":
                            helper_main.openFile(activity, pathFile, "application/x-rar-compressed", view);
                            break;
                        case ".epub":
                            helper_main.openFile(activity, pathFile, "application/epub+zip", view);
                            break;
                        case ".cbz":
                            helper_main.openFile(activity, pathFile, "application/x-cbz", view);
                            break;
                        case ".cbr":
                            helper_main.openFile(activity, pathFile, "application/x-cbr", view);
                            break;
                        case ".fb2":
                            helper_main.openFile(activity, pathFile, "application/x-fb2", view);
                            break;
                        case ".rtf":
                            helper_main.openFile(activity, pathFile, "application/rtf", view);
                            break;
                        case ".opml":
                            helper_main.openFile(activity, pathFile, "application/opml", view);
                            break;

                        default:
                            Toast.makeText(activity, text, Toast.LENGTH_SHORT).show();
                            break;
                        }

                        String dir = pathFile.getParentFile().getAbsolutePath();
                        helper_main.openFilePicker(activity, view, dir);
                    }
                    if (options[item].equals(activity.getString(R.string.choose_menu_2))) {

                        if (pathFile.exists()) {
                            Intent sharingIntent = new Intent(Intent.ACTION_SEND);
                            sharingIntent.setType("image/png");
                            sharingIntent.putExtra(Intent.EXTRA_SUBJECT, fileName);
                            sharingIntent.putExtra(Intent.EXTRA_TEXT, fileName);
                            Uri bmpUri = Uri.fromFile(pathFile);
                            sharingIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
                            activity.startActivity(Intent.createChooser(sharingIntent,
                                    (activity.getString(R.string.app_share_file))));
                        }
                        String dir = pathFile.getParentFile().getAbsolutePath();
                        helper_main.openFilePicker(activity, view, dir);
                    }
                    if (options[item].equals(activity.getString(R.string.choose_menu_4))) {
                        final AlertDialog.Builder dialog2 = new AlertDialog.Builder(activity);

                        dialog2.setMessage(activity.getString(R.string.choose_delete));
                        dialog2.setPositiveButton(R.string.toast_yes, new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int whichButton) {
                                pathFile.delete();
                                new Handler().postDelayed(new Runnable() {
                                    public void run() {
                                        String dir = pathFile.getParentFile().getAbsolutePath();
                                        helper_main.openFilePicker(activity, view, dir);
                                    }
                                }, 500);
                            }
                        });
                        dialog2.setNegativeButton(R.string.toast_cancel, new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int whichButton) {
                                dialog.cancel();
                            }
                        });
                        dialog2.setOnCancelListener(new DialogInterface.OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface dialog) {
                                // dialog dismiss without button press
                                String dir = pathFile.getParentFile().getAbsolutePath();
                                helper_main.openFilePicker(activity, view, dir);
                            }
                        });
                        dialog2.show();
                    }
                    if (options[item].equals(activity.getString(R.string.choose_menu_3))) {

                        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                        View dialogView = View.inflate(activity, R.layout.dialog_edit_file, null);

                        final EditText edit_title = (EditText) dialogView.findViewById(R.id.pass_title);

                        builder.setView(dialogView);
                        builder.setTitle(R.string.choose_title);
                        builder.setPositiveButton(R.string.toast_yes, new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int whichButton) {

                                String inputTag = edit_title.getText().toString().trim();

                                File dir = pathFile.getParentFile();
                                File to = new File(dir, inputTag + fileExtension);

                                pathFile.renameTo(to);
                                pathFile.delete();

                                new Handler().postDelayed(new Runnable() {
                                    public void run() {
                                        String dir = pathFile.getParentFile().getAbsolutePath();
                                        helper_main.openFilePicker(activity, view, dir);
                                    }
                                }, 500);
                            }
                        });
                        builder.setNegativeButton(R.string.toast_cancel, new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int whichButton) {
                                dialog.cancel();
                            }
                        });
                        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface dialog) {
                                // dialog dismiss without button press
                                String dir = pathFile.getParentFile().getAbsolutePath();
                                helper_main.openFilePicker(activity, view, dir);
                            }
                        });

                        final AlertDialog dialog2 = builder.create();
                        // Display the custom alert dialog on interface
                        dialog2.show();
                        helper_editText.showKeyboard(activity, edit_title, 0, fileNameWE,
                                activity.getString(R.string.choose_hint));
                    }
                }
            });
            dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    // dialog dismiss without button press
                    String dir = pathFile.getParentFile().getAbsolutePath();
                    helper_main.openFilePicker(activity, view, dir);
                }
            });
            dialog.show();
        }
    }).build().show();
}

From source file:de.baumann.hhsmoodle.data_count.Count_Fragment.java

public void setCountList() {

    if (isFABOpen) {
        closeFABMenu();//from w  w  w .j  a v  a 2 s.  co m
    }

    //display data
    final int layoutstyle = R.layout.list_item_notes;
    int[] xml_id = new int[] { R.id.textView_title_notes, R.id.textView_des_notes, R.id.textView_create_notes };
    String[] column = new String[] { "count_title", "count_content", "count_creation" };
    final Cursor row = db.fetchAllData(getActivity());
    adapter = new SimpleCursorAdapter(getActivity(), layoutstyle, row, column, xml_id, 0) {
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            Cursor row2 = (Cursor) lv.getItemAtPosition(position);
            final String _id = row2.getString(row2.getColumnIndexOrThrow("_id"));
            final String count_title = row2.getString(row2.getColumnIndexOrThrow("count_title"));
            final String count_content = row2.getString(row2.getColumnIndexOrThrow("count_content"));
            final String count_icon = row2.getString(row2.getColumnIndexOrThrow("count_icon"));
            final String count_attachment = row2.getString(row2.getColumnIndexOrThrow("count_attachment"));
            final String count_creation = row2.getString(row2.getColumnIndexOrThrow("count_creation"));

            View v = super.getView(position, convertView, parent);
            final TextView tv = (TextView) v.findViewById(R.id.text);

            if (count_attachment.isEmpty()) {

                tv.setText(count_content);

                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        int n = tv.getLineCount();

                        StringBuilder sb = new StringBuilder(n);
                        for (int i = 0; i < n; ++i) {
                            sb.append("0" + '\n');
                        }
                        String result = sb.toString();

                        db.update(Integer.parseInt(_id), count_title, count_content, count_icon, result,
                                count_creation);
                        setCountList();
                    }
                }, 500);
            }

            ImageView iv_icon = (ImageView) v.findViewById(R.id.icon_notes);
            helper_main.switchIcon(getActivity(), count_icon, "count_icon", iv_icon);

            iv_icon.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {

                    final helper_main.Item[] items = {
                            new helper_main.Item(getString(R.string.note_priority_0), R.drawable.circle_green),
                            new helper_main.Item(getString(R.string.note_priority_1), R.drawable.circle_yellow),
                            new helper_main.Item(getString(R.string.note_priority_2), R.drawable.circle_red), };

                    ListAdapter adapter = new ArrayAdapter<helper_main.Item>(getActivity(),
                            android.R.layout.select_dialog_item, android.R.id.text1, items) {
                        @NonNull
                        public View getView(int position, View convertView, @NonNull ViewGroup parent) {
                            //Use super class to create the View
                            View v = super.getView(position, convertView, parent);
                            TextView tv = (TextView) v.findViewById(android.R.id.text1);
                            tv.setTextSize(18);
                            tv.setCompoundDrawablesWithIntrinsicBounds(items[position].icon, 0, 0, 0);
                            //Add margin between image and text (support various screen densities)
                            int dp5 = (int) (24 * getResources().getDisplayMetrics().density + 0.5f);
                            tv.setCompoundDrawablePadding(dp5);

                            return v;
                        }
                    };

                    new AlertDialog.Builder(getActivity())
                            .setPositiveButton(R.string.toast_cancel, new DialogInterface.OnClickListener() {

                                public void onClick(DialogInterface dialog, int whichButton) {
                                    dialog.cancel();
                                }
                            }).setAdapter(adapter, new DialogInterface.OnClickListener() {

                                public void onClick(DialogInterface dialog, int item) {
                                    if (item == 0) {
                                        db.update(Integer.parseInt(_id), count_title, count_content, "3",
                                                count_attachment, count_creation);
                                        setCountList();
                                    } else if (item == 1) {
                                        db.update(Integer.parseInt(_id), count_title, count_content, "2",
                                                count_attachment, count_creation);
                                        setCountList();
                                    } else if (item == 2) {
                                        db.update(Integer.parseInt(_id), count_title, count_content, "1",
                                                count_attachment, count_creation);
                                        setCountList();
                                    }
                                }
                            }).show();
                }
            });
            return v;
        }
    };

    //display data by filter
    final String note_search = sharedPref.getString("filter_countBY", "note_title");
    sharedPref.edit().putString("filter_countBY", "note_title").apply();
    filter.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
            adapter.getFilter().filter(s.toString());
        }
    });
    adapter.setFilterQueryProvider(new FilterQueryProvider() {
        public Cursor runQuery(CharSequence constraint) {
            return db.fetchDataByFilter(constraint.toString(), note_search);
        }
    });

    lv.setAdapter(adapter);
    //onClick function
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterview, View view, int position, long id) {

            if (isFABOpen) {
                closeFABMenu();
            }

            Cursor row2 = (Cursor) lv.getItemAtPosition(position);
            final String _id = row2.getString(row2.getColumnIndexOrThrow("_id"));
            final String count_title = row2.getString(row2.getColumnIndexOrThrow("count_title"));
            final String count_content = row2.getString(row2.getColumnIndexOrThrow("count_content"));
            final String count_icon = row2.getString(row2.getColumnIndexOrThrow("count_icon"));
            final String count_attachment = row2.getString(row2.getColumnIndexOrThrow("count_attachment"));
            final String count_creation = row2.getString(row2.getColumnIndexOrThrow("count_creation"));

            sharedPref.edit().putString("count_title", count_title).apply();
            sharedPref.edit().putString("count_content", count_content).apply();
            sharedPref.edit().putString("count_seqno", _id).apply();
            sharedPref.edit().putString("count_icon", count_icon).apply();
            sharedPref.edit().putString("count_create", count_creation).apply();
            sharedPref.edit().putString("count_attachment", count_attachment).apply();

            helper_main.switchToActivity(getActivity(), Activity_count.class, false);
        }
    });

    lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

            if (isFABOpen) {
                closeFABMenu();
            }

            Cursor row2 = (Cursor) lv.getItemAtPosition(position);
            final String _id = row2.getString(row2.getColumnIndexOrThrow("_id"));
            final String count_title = row2.getString(row2.getColumnIndexOrThrow("count_title"));
            final String count_content = row2.getString(row2.getColumnIndexOrThrow("count_content"));
            final String count_icon = row2.getString(row2.getColumnIndexOrThrow("count_icon"));
            final String count_attachment = row2.getString(row2.getColumnIndexOrThrow("count_attachment"));
            final String count_creation = row2.getString(row2.getColumnIndexOrThrow("count_creation"));

            final CharSequence[] options = { getString(R.string.number_edit_entry),
                    getString(R.string.bookmark_remove_bookmark), getString(R.string.todo_share),
                    getString(R.string.bookmark_createNote), getString(R.string.bookmark_createEvent) };
            new AlertDialog.Builder(getActivity())
                    .setPositiveButton(R.string.toast_cancel, new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int whichButton) {
                            dialog.cancel();
                        }
                    }).setItems(options, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int item) {
                            if (options[item].equals(getString(R.string.number_edit_entry))) {

                                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                                View dialogView = View.inflate(getActivity(), R.layout.dialog_edit_title, null);

                                final EditText edit_title = (EditText) dialogView.findViewById(R.id.pass_title);
                                edit_title.setHint(R.string.bookmark_edit_title);
                                edit_title.setText(count_title);

                                builder.setView(dialogView);
                                builder.setTitle(R.string.bookmark_edit_title);
                                builder.setPositiveButton(R.string.toast_yes,
                                        new DialogInterface.OnClickListener() {

                                            public void onClick(DialogInterface dialog, int whichButton) {

                                                String inputTag = edit_title.getText().toString().trim();
                                                db.update(Integer.parseInt(_id), inputTag, count_content,
                                                        count_icon, count_attachment, count_creation);
                                                setCountList();
                                                Snackbar.make(lv, R.string.bookmark_added,
                                                        Snackbar.LENGTH_SHORT).show();
                                            }
                                        });
                                builder.setNegativeButton(R.string.toast_cancel,
                                        new DialogInterface.OnClickListener() {

                                            public void onClick(DialogInterface dialog, int whichButton) {
                                                dialog.cancel();
                                            }
                                        });

                                final AlertDialog dialog2 = builder.create();
                                // Display the custom alert dialog on interface
                                dialog2.show();
                                helper_main.showKeyboard(getActivity(), edit_title);
                            }

                            if (options[item].equals(getString(R.string.todo_share))) {
                                Intent sharingIntent = new Intent(Intent.ACTION_SEND);
                                sharingIntent.setType("text/plain");
                                sharingIntent.putExtra(Intent.EXTRA_SUBJECT, count_title);
                                sharingIntent.putExtra(Intent.EXTRA_TEXT, count_content);
                                startActivity(Intent.createChooser(sharingIntent,
                                        (getString(R.string.note_share_2))));
                            }

                            if (options[item].equals(getString(R.string.bookmark_createEvent))) {
                                helper_main.createCalendarEvent(getActivity(), count_title, count_content);
                            }

                            if (options[item].equals(getString(R.string.bookmark_remove_bookmark))) {
                                Snackbar snackbar = Snackbar
                                        .make(lv, R.string.note_remove_confirmation, Snackbar.LENGTH_LONG)
                                        .setAction(R.string.toast_yes, new View.OnClickListener() {
                                            @Override
                                            public void onClick(View view) {
                                                db.delete(Integer.parseInt(_id));
                                                setCountList();
                                            }
                                        });
                                snackbar.show();
                            }

                            if (options[item].equals(getString(R.string.bookmark_createNote))) {
                                Notes_helper.newNote(getActivity(), count_title, count_content, "", "", "", "");
                            }

                        }
                    }).show();

            return true;
        }
    });
}

From source file:com.krayzk9s.imgurholo.ui.SingleImageFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    final ImgurHoloActivity activity = (ImgurHoloActivity) getActivity();
    final SharedPreferences settings = activity.getApiCall().settings;
    sort = settings.getString("CommentSort", "Best");
    boolean newData = true;
    if (commentData != null) {
        newData = false;//  w  w  w. j  a  va  2s .  c  o  m
    }

    mainView = inflater.inflate(R.layout.single_image_layout, container, false);
    String[] mMenuList = getResources().getStringArray(R.array.emptyList);
    if (commentAdapter == null)
        commentAdapter = new CommentAdapter(mainView.getContext());
    commentLayout = (ListView) mainView.findViewById(R.id.comment_thread);
    commentLayout.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    if (settings.getString("theme", MainActivity.HOLO_LIGHT).equals(MainActivity.HOLO_LIGHT))
        imageLayoutView = (LinearLayout) View.inflate(getActivity(), R.layout.image_view, null);
    else
        imageLayoutView = (LinearLayout) View.inflate(getActivity(), R.layout.dark_image_view, null);

    mPullToRefreshLayout = (PullToRefreshLayout) mainView.findViewById(R.id.ptr_layout);
    ActionBarPullToRefresh.from(getActivity())
            // Mark All Children as pullable
            .allChildrenArePullable()
            // Set the OnRefreshListener
            .listener(this)
            // Finally commit the setup to our PullToRefreshLayout
            .setup(mPullToRefreshLayout);
    if (savedInstanceState != null && newData) {
        imageData = savedInstanceState.getParcelable("imageData");
        inGallery = savedInstanceState.getBoolean("inGallery");
    }
    LinearLayout layout = (LinearLayout) imageLayoutView.findViewById(R.id.image_buttons);
    TextView imageDetails = (TextView) imageLayoutView.findViewById(R.id.single_image_details);
    layout.setVisibility(View.VISIBLE);
    ImageButton imageFullscreen = (ImageButton) imageLayoutView.findViewById(R.id.fullscreen);
    imageUpvote = (ImageButton) imageLayoutView.findViewById(R.id.rating_good);
    imageDownvote = (ImageButton) imageLayoutView.findViewById(R.id.rating_bad);
    ImageButton imageFavorite = (ImageButton) imageLayoutView.findViewById(R.id.rating_favorite);
    imageComment = (ImageButton) imageLayoutView.findViewById(R.id.comment);
    ImageButton imageUser = (ImageButton) imageLayoutView.findViewById(R.id.user);
    imageScore = (TextView) imageLayoutView.findViewById(R.id.single_image_score);
    TextView imageInfo = (TextView) imageLayoutView.findViewById(R.id.single_image_info);
    Log.d("imageData", imageData.getJSONObject().toString());
    if (imageData.getJSONObject().has("ups")) {
        imageUpvote.setVisibility(View.VISIBLE);
        imageDownvote.setVisibility(View.VISIBLE);
        imageScore.setVisibility(View.VISIBLE);
        imageComment.setVisibility(View.VISIBLE);
        ImageUtils.updateImageFont(imageData, imageScore);
    }
    imageInfo.setVisibility(View.VISIBLE);
    ImageUtils.updateInfoFont(imageData, imageInfo);
    imageUser.setVisibility(View.VISIBLE);
    imageFavorite.setVisibility(View.VISIBLE);
    try {
        if (!imageData.getJSONObject().has("account_url")
                || imageData.getJSONObject().getString("account_url").equals("null")
                || imageData.getJSONObject().getString("account_url").equals("[deleted]"))
            imageUser.setVisibility(View.GONE);
        if (!imageData.getJSONObject().has("vote")) {
            imageUpvote.setVisibility(View.GONE);
            imageDownvote.setVisibility(View.GONE);
        } else {
            if (imageData.getJSONObject().getString("vote") != null
                    && imageData.getJSONObject().getString("vote").equals("up"))
                imageUpvote.setImageResource(R.drawable.green_rating_good);
            else if (imageData.getJSONObject().getString("vote") != null
                    && imageData.getJSONObject().getString("vote").equals("down"))
                imageDownvote.setImageResource(R.drawable.red_rating_bad);
        }
        if (imageData.getJSONObject().getString("favorite") != null
                && imageData.getJSONObject().getBoolean("favorite"))
            imageFavorite.setImageResource(R.drawable.green_rating_favorite);
    } catch (JSONException e) {
        Log.e("Error!", e.toString());
    }
    imageFavorite.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ImageUtils.favoriteImage(singleImageFragment, imageData, (ImageButton) view, activity.getApiCall());
        }
    });
    imageUser.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ImageUtils.gotoUser(singleImageFragment, imageData);
        }
    });
    imageComment.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Activity activity = getActivity();
            final EditText newBody = new EditText(activity);
            newBody.setHint(R.string.body_hint_body);
            newBody.setLines(3);
            final TextView characterCount = new TextView(activity);
            characterCount.setText("140");
            LinearLayout commentReplyLayout = new LinearLayout(activity);
            newBody.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
                    //
                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
                    characterCount.setText(String.valueOf(140 - charSequence.length()));
                }

                @Override
                public void afterTextChanged(Editable editable) {
                    for (int i = editable.length(); i > 0; i--) {
                        if (editable.subSequence(i - 1, i).toString().equals("\n"))
                            editable.replace(i - 1, i, "");
                    }
                }
            });
            commentReplyLayout.setOrientation(LinearLayout.VERTICAL);
            commentReplyLayout.addView(newBody);
            commentReplyLayout.addView(characterCount);
            new AlertDialog.Builder(activity).setTitle(R.string.dialog_comment_on_image_title)
                    .setView(commentReplyLayout)
                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            if (newBody.getText() != null && newBody.getText().toString().length() < 141) {
                                HashMap<String, Object> commentMap = new HashMap<String, Object>();
                                try {
                                    commentMap.put("comment", newBody.getText().toString());
                                    commentMap.put("image_id", imageData.getJSONObject().getString("id"));
                                    Fetcher fetcher = new Fetcher(singleImageFragment, "3/comment/",
                                            ApiCall.POST, commentMap,
                                            ((ImgurHoloActivity) getActivity()).getApiCall(), POSTCOMMENT);
                                    fetcher.execute();
                                } catch (JSONException e) {
                                    Log.e("Error!", e.toString());
                                }
                            }
                        }
                    }).setNegativeButton(R.string.dialog_answer_cancel, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            // Do nothing.
                        }
                    }).show();
        }
    });
    imageUpvote.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ImageUtils.upVote(singleImageFragment, imageData, imageUpvote, imageDownvote,
                    activity.getApiCall());
            ImageUtils.updateImageFont(imageData, imageScore);
        }
    });
    imageDownvote.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ImageUtils.downVote(singleImageFragment, imageData, imageUpvote, imageDownvote,
                    activity.getApiCall());
            ImageUtils.updateImageFont(imageData, imageScore);
        }
    });
    if (popupWindow != null) {
        popupWindow.dismiss();
    }
    popupWindow = new PopupWindow();
    imageFullscreen.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ImageUtils.fullscreen(singleImageFragment, imageData, popupWindow, mainView);
        }
    });
    ArrayAdapter<String> tempAdapter = new ArrayAdapter<String>(mainView.getContext(),
            R.layout.drawer_list_item, mMenuList);
    Log.d("URI", "YO I'M IN YOUR SINGLE FRAGMENT gallery:" + inGallery);
    imageView = (ImageView) imageLayoutView.findViewById(R.id.single_image_view);
    loadImage();
    TextView imageTitle = (TextView) imageLayoutView.findViewById(R.id.single_image_title);
    TextView imageDescription = (TextView) imageLayoutView.findViewById(R.id.single_image_description);

    try {
        String size = String
                .valueOf(NumberFormat.getIntegerInstance()
                        .format(imageData.getJSONObject().getInt(ImgurHoloActivity.IMAGE_DATA_WIDTH)))
                + "x"
                + NumberFormat.getIntegerInstance()
                        .format(imageData.getJSONObject().getInt(ImgurHoloActivity.IMAGE_DATA_HEIGHT))
                + " (" + NumberFormat.getIntegerInstance()
                        .format(imageData.getJSONObject().getInt(ImgurHoloActivity.IMAGE_DATA_SIZE))
                + "B)";
        String initial = imageData.getJSONObject().getString(ImgurHoloActivity.IMAGE_DATA_TYPE) + " "
                + Html.fromHtml("&#8226;") + " " + size + " " + Html.fromHtml("&#8226;") + " " + "Views: "
                + NumberFormat.getIntegerInstance()
                        .format(imageData.getJSONObject().getInt(ImgurHoloActivity.IMAGE_DATA_VIEWS));
        imageDetails.setText(initial);
        Log.d("imagedata", imageData.getJSONObject().toString());
        if (!imageData.getJSONObject().getString(ImgurHoloActivity.IMAGE_DATA_TITLE).equals("null"))
            imageTitle.setText(imageData.getJSONObject().getString(ImgurHoloActivity.IMAGE_DATA_TITLE));
        else
            imageTitle.setVisibility(View.GONE);
        if (!imageData.getJSONObject().getString(ImgurHoloActivity.IMAGE_DATA_DESCRIPTION).equals("null")) {
            imageDescription
                    .setText(imageData.getJSONObject().getString(ImgurHoloActivity.IMAGE_DATA_DESCRIPTION));
            imageDescription.setVisibility(View.VISIBLE);
        } else
            imageDescription.setVisibility(View.GONE);
        commentLayout.addHeaderView(imageLayoutView);
        commentLayout.setAdapter(tempAdapter);
    } catch (JSONException e) {
        Log.e("Text Error!", e.toString());
    }
    if ((savedInstanceState == null || commentData == null) && newData) {
        commentData = new JSONParcelable();
        getComments();
        commentLayout.setAdapter(commentAdapter);
    } else if (newData) {
        commentArray = savedInstanceState.getParcelableArrayList("commentData");
        commentAdapter.addAll(commentArray);
        commentLayout.setAdapter(commentAdapter);
        commentAdapter.notifyDataSetChanged();
    } else if (commentArray != null) {
        commentAdapter.addAll(commentArray);
        commentLayout.setAdapter(commentAdapter);
        commentAdapter.notifyDataSetChanged();
    }
    return mainView;
}