Example usage for android.widget LinearLayout VERTICAL

List of usage examples for android.widget LinearLayout VERTICAL

Introduction

In this page you can find the example usage for android.widget LinearLayout VERTICAL.

Prototype

int VERTICAL

To view the source code for android.widget LinearLayout VERTICAL.

Click Source Link

Usage

From source file:com.cssn.samplesdk.MainActivity.java

/**
 * Updates the card's frame layout, shows/hides the back side card frame,
 * highlights the selected option, and load the card images in the view.
 *///from w  w w. j a  va  2 s.  com
public void updateUI() {
    if (Utils.LOG_ENABLED) {
        Utils.appendLog(TAG, "private void updateUI()");
    }

    if (mainActivityModel.getErrorMessage() != null) {
        Util.dismissDialog(alertDialog);

        alertDialog = Util.showDialog(this, mainActivityModel.getErrorMessage(),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mainActivityModel.setErrorMessage(null);
                        isShowErrorAlertDialog = false;
                    }
                });
        isShowErrorAlertDialog = true;
    }

    // change orientation issues
    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        layoutCards.setOrientation(LinearLayout.HORIZONTAL);
    } else {
        layoutCards.setOrientation(LinearLayout.VERTICAL);
    }

    // enable/disable the activate button
    updateActivateLicenseButtonFromModel();

    if (mainActivityModel.getCurrentOptionType() == -1) {
        // do not do any extra processing
        return;
    }

    // calculate the width and height of the front side card image and resize them
    resizeImageFrames(mainActivityModel.getCurrentOptionType());

    // show/hide the front and back views in the layout
    switch (mainActivityModel.getCurrentOptionType()) {
    case CardType.PASSPORT:
        txtTapToCaptureFront.setText(getResources().getString(R.string.tap_to_capture));
        showFrontSideCardImage();
        hideBackSideCardImage();
        break;

    case CardType.DRIVERS_LICENSE:
        showFrontSideCardImage();
        if (mainActivityModel.getBackSideCardImage() != null) {
            showBackSideCardImage();
        } else {
            hideBackSideCardImage();
        }
        break;

    case CardType.MEDICAL_INSURANCE:
        txtTapToCaptureFront.setText(R.string.tap_to_capture_front_side);
        showFrontSideCardImage();
        showBackSideCardImage();
        break;
    case CardType.FACIAL_RECOGNITION:
        showFrontSideCardImage();
        if (mainActivityModel.getBackSideCardImage() != null) {
            showBackSideCardImage();
        } else {
            hideBackSideCardImage();
        }
        break;

    default:
        throw new IllegalArgumentException(
                "This method is wrong implemented, there is not processing for the card type '"
                        + mainActivityModel.getCurrentOptionType() + "'");

    }

    // update card in front image view
    frontImageView.setImageBitmap(Util.getRoundedCornerBitmap(mainActivityModel.getFrontSideCardImage(),
            this.getApplicationContext()));

    if (mainActivityModel.getFrontSideCardImage() != null) {
        hideFrontImageText();
    } else {
        showFrontImageText();
    }

    // update card in back image view
    backImageView.setImageBitmap(Util.getRoundedCornerBitmap(mainActivityModel.getBackSideCardImage(),
            this.getApplicationContext()));

    if (mainActivityModel.getBackSideCardImage() != null) {
        hideBackImageText();
    } else {
        showBackImageText();
    }

    // update the process button
    if (mainActivityModel.getFrontSideCardImage() != null) {
        processCardButton.setVisibility(View.VISIBLE);
    } else {
        processCardButton.setVisibility(View.GONE);
    }

    highlightCurrentCardOption();

}

From source file:edu.pitt.gis.uniapp.UniApp.java

/**
 * Shows the splash screen over the full Activity
 *///w w w  .j  a  v  a 2 s .  c om
@SuppressWarnings("deprecation")
protected void showSplashScreen(final int time) {
    final UniApp that = this;

    Runnable runnable = new Runnable() {
        public void run() {
            // Get reference to display
            Display display = getWindowManager().getDefaultDisplay();

            // Create the layout for the dialog
            LinearLayout root = new LinearLayout(that.getActivity());
            root.setMinimumHeight(display.getHeight());
            root.setMinimumWidth(display.getWidth());
            root.setOrientation(LinearLayout.VERTICAL);
            root.setBackgroundColor(that.getIntegerProperty("backgroundColor", Color.BLACK));
            root.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                    ViewGroup.LayoutParams.FILL_PARENT, 0.0F));
            root.setBackgroundResource(that.splashscreen);

            // Create and show the dialog
            splashDialog = new Dialog(that, android.R.style.Theme_Translucent_NoTitleBar);
            // check to see if the splash screen should be full screen
            if ((getWindow().getAttributes().flags
                    & WindowManager.LayoutParams.FLAG_FULLSCREEN) == WindowManager.LayoutParams.FLAG_FULLSCREEN) {
                splashDialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                        WindowManager.LayoutParams.FLAG_FULLSCREEN);
            }
            splashDialog.setContentView(root);
            splashDialog.setCancelable(false);
            splashDialog.show();

            // Set Runnable to remove splash screen just in case
            final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                public void run() {
                    removeSplashScreen();
                }
            }, time);
        }
    };
    this.runOnUiThread(runnable);
}

From source file:terse.a1.TerseActivity.java

private void viewPath9display(String path, LayoutParams widgetParams) {
    String explain;/*w  w w  . j ava2s . c om*/
    if (terp_error != null) {
        explain = "terp_error = " + terp_error;
    } else {
        try {
            terp.say("Sending to terp: %s", path);
            final Dict d = terp.handleUrl(path, taQuery);
            explain = "DEFAULT EXPLANATION:\n\n" + d.toString();

            Str TYPE = d.cls.terp.newStr("type");
            Str VALUE = d.cls.terp.newStr("value");
            Str TITLE = d.cls.terp.newStr("title");
            Str type = (Str) d.dict.get(TYPE);
            Ur value = d.dict.get(VALUE);
            Ur title = d.dict.get(TITLE);

            // {
            // double ticks = Static.floatAt(d, "ticks", -1);
            // double nanos = Static.floatAt(d, "nanos", -1);
            // Toast.makeText(
            // getApplicationContext(),
            // Static.fmt("%d ticks, %.3f secs", (long) ticks,
            // (double) nanos / 1e9), Toast.LENGTH_SHORT)
            // .show();
            // }

            if (type.str.equals("list") && value instanceof Vec) {
                final ArrayList<Ur> v = ((Vec) value).vec;
                final ArrayList<String> labels = new ArrayList<String>();
                final ArrayList<String> links = new ArrayList<String>();
                for (int i = 0; i < v.size(); i++) {
                    Ur item = v.get(i);
                    String label = item instanceof Str ? ((Str) item).str : item.toString();
                    if (item instanceof Vec && ((Vec) item).vec.size() == 2) {
                        // OLD STYLE
                        label = ((Vec) item).vec.get(0).toString();
                        Matcher m = LINK_P.matcher(label);
                        if (m.lookingAt()) {
                            label = m.group(2) + " " + m.group(3);
                        }
                        label += "    [" + ((Vec) item).vec.get(1).toString().length() + "]";
                        links.add(null); // Use old style, not links.
                    } else {
                        // NEW STYLE
                        label = item.toString();
                        if (label.charAt(0) == '/') {
                            String link = Terp.WHITE_PLUS.split(label, 2)[0];
                            links.add(link);
                        } else {
                            links.add("");
                        }
                    }
                    labels.add(label);
                }
                if (labels.size() != links.size())
                    terp.toss("lables#%d links#%d", labels.size(), links.size());

                ListView listv = new ListView(this);
                listv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, labels));
                listv.setLayoutParams(widgetParams);
                listv.setTextFilterEnabled(true);

                listv.setOnItemClickListener(new OnItemClickListener() {
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        // When clicked, show a toast with the TextView text
                        // Toast.makeText(getApplicationContext(),
                        // ((TextView) view).getText(),
                        // Toast.LENGTH_SHORT).show();
                        String toast_text = ((TextView) view).getText().toString();
                        // if (v.get(position) instanceof Vec) {
                        if (links.get(position) == null) {
                            // OLD STYLE
                            Vec pair = (Vec) v.get(position);
                            if (pair.vec.size() == 2) {
                                if (pair.vec.get(0) instanceof Str) {
                                    String[] words = ((Str) pair.vec.get(0)).str.split("\\|");
                                    Log.i("TT-WORDS", terp.arrayToString(words));
                                    toast_text += "\n\n" + Static.arrayToString(words);
                                    if (words[1].equals("link")) {
                                        Uri uri = new Uri.Builder().scheme("terse").path(words[2]).build();
                                        Intent intent = new Intent("android.intent.action.MAIN", uri);
                                        intent.setClass(getApplicationContext(), TerseActivity.class);

                                        startActivity(intent);
                                    }
                                }
                            }
                        } else {
                            // NEW STYLE
                            terp.say("NEW STYLE LIST SELECT #%d link=<%s> label=<%s>", position,
                                    links.get(position), labels.get(position));
                            if (links.get(position).length() > 0) {
                                Uri uri = new Uri.Builder().scheme("terse").path(links.get(position)).build();
                                Intent intent = new Intent("android.intent.action.MAIN", uri);
                                intent.setClass(getApplicationContext(), TerseActivity.class);

                                startActivity(intent);
                            }
                        }
                        // }
                        // Toast.makeText(getApplicationContext(),
                        // ((TextView) view).getText(),
                        // Toast.LENGTH_SHORT).show();
                    }
                });
                setContentView(listv);
                return;
            } else if (type.str.equals("edit") && value instanceof Str) {
                final EditText ed = new EditText(this);

                ed.setText(taSaveMe == null ? value.toString() : taSaveMe);

                ed.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE
                        | InputType.TYPE_TEXT_VARIATION_LONG_MESSAGE | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
                ed.setLayoutParams(widgetParams);
                // ed.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22);
                ed.setTextAppearance(this, R.style.teletype);
                ed.setBackgroundColor(Color.BLACK);
                ed.setGravity(Gravity.TOP);
                ed.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_INSET);
                ed.setVerticalFadingEdgeEnabled(true);
                ed.setVerticalScrollBarEnabled(true);
                ed.setOnKeyListener(new OnKeyListener() {
                    public boolean onKey(View v, int keyCode, KeyEvent event) {
                        // If the event is a key-down event on the "enter"
                        // button
                        // if ((event.getAction() == KeyEvent.ACTION_DOWN)
                        // &&
                        // (keyCode == KeyEvent.KEYCODE_ENTER)) {
                        // // Perform action on key press
                        // Toast.makeText(TerseActivity.this, ed.getText(),
                        // Toast.LENGTH_SHORT).show();
                        // return true;
                        // }
                        return false;
                    }
                });

                Button btn = new Button(this);
                btn.setText("Save");
                btn.setOnClickListener(new OnClickListener() {
                    public void onClick(View v) {
                        // Perform action on clicks
                        String text = ed.getText().toString();
                        text = Parser.charSubsts(text);
                        Toast.makeText(TerseActivity.this, text, Toast.LENGTH_SHORT).show();
                        String action = stringAt(d, "action");
                        String query = "";

                        String f1 = stringAt(d, "field1");
                        String v1 = stringAt(d, "value1");
                        String f2 = stringAt(d, "field2");
                        String v2 = stringAt(d, "value2");
                        f1 = (f1 == null) ? "f1null" : f1;
                        v1 = (v1 == null) ? "v1null" : v1;
                        f2 = (f2 == null) ? "f2null" : f2;
                        v2 = (v2 == null) ? "v2null" : v2;

                        startTerseActivity(action, query, stringAt(d, "field1"), stringAt(d, "value1"),
                                stringAt(d, "field2"), stringAt(d, "value2"), "text", text);
                    }
                });

                LinearLayout linear = new LinearLayout(this);
                linear.setOrientation(LinearLayout.VERTICAL);
                linear.addView(btn);
                linear.addView(ed);
                setContentView(linear);
                return;

            } else if (type.str.equals("draw") && value instanceof Vec) {
                Vec v = ((Vec) value);
                DrawView dv = new DrawView(this, v.vec, d);
                dv.setLayoutParams(widgetParams);
                setContentView(dv);
                return;
            } else if (type.str.equals("live")) {
                Blk blk = value.mustBlk();
                Blk event = Static.urAt(d, "event").asBlk();
                TerseSurfView tsv = new TerseSurfView(this, blk, event);
                setContentView(tsv);
                return;
            } else if (type.str.equals("fnord")) {
                Blk blk = value.mustBlk();
                Blk event = Static.urAt(d, "event").asBlk();
                FnordView fnord = new FnordView(this, blk, event);
                setContentView(fnord);
                return;
            } else if (type.str.equals("world") && value instanceof Str) {
                String newWorld = value.toString();
                if (Terp.WORLD_P.matcher(newWorld).matches()) {
                    world = newWorld;
                    resetTerp();
                    explain = Static.fmt("Switching to world <%s>\nUse menu to go Home.", world);
                    Toast.makeText(getApplicationContext(), explain, Toast.LENGTH_LONG).show();
                } else {
                    terp.toss("Bad world syntax (must be 3 letters then 0 to 3 digits: <%s>", newWorld);
                }
                // Fall thru for explainv.setText(explain).
            } else if (type.str.equals("text")) {
                explain = "<<< " + title + " >>>\n\n" + value.toString();
                // Fall thru for explainv.setText(explain).
            } else if (type.str.equals("html")) {
                final WebView webview = new WebView(this);
                // webview.loadData(value.toString(), "text/html", null);
                webview.loadDataWithBaseURL("terse://terse", value.toString(), "text/html", "UTF-8", null);
                webview.setWebViewClient(new WebViewClient() {
                    @Override
                    public boolean shouldOverrideUrlLoading(WebView view, String url) {
                        // terp.say("WebView UrlLoading: url=%s", url);
                        URI uri = URI.create("" + url);
                        // terp.say("WebView UrlLoading: URI=%s", uri);
                        terp.say("WebView UrlLoading: getPath=%s", uri.getPath());
                        terp.say("WebView UrlLoading: getQuery=%s", uri.getQuery());

                        // Toast.makeText(getApplicationContext(),
                        // uri.toASCIIString(), Toast.LENGTH_SHORT)
                        // .show();
                        // webview.invalidate();
                        //
                        // TextView quick = new
                        // TextView(TerseActivity.this);
                        // quick.setText(uri.toASCIIString());
                        // quick.setBackgroundColor(Color.BLACK);
                        // quick.setTextColor(Color.WHITE);
                        // setContentView(quick);

                        startTerseActivity(uri.getPath(), uri.getQuery());

                        return true;
                    }
                });

                // webview.setWebChromeClient(new WebChromeClient());
                webview.getSettings().setBuiltInZoomControls(true);
                // webview.getSettings().setJavaScriptEnabled(true);
                webview.getSettings().setDefaultFontSize(18);
                webview.getSettings().setNeedInitialFocus(true);
                webview.getSettings().setSupportZoom(true);
                webview.getSettings().setSaveFormData(true);
                setContentView(webview);

                // ScrollView scrollv = new ScrollView(this);
                // scrollv.addView(webview);
                // setContentView(scrollv);
                return;
            } else {
                explain = "Unknown page type: " + type.str + " with vaule type: " + value.cls
                        + "\n\n##############\n\n";
                explain += value.toString();
                // Fall thru for explainv.setText(explain).
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            explain = Static.describe(ex);
        }
    }

    TextView explainv = new TextView(this);
    explainv.setText(explain);
    explainv.setBackgroundColor(Color.BLACK);
    explainv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24);
    explainv.setTextColor(Color.YELLOW);

    SetContentViewWithHomeButtonAndScroll(explainv);
}

From source file:net.bluehack.ui.MediaActivity.java

@Override
public View createView(Context context) {
    actionBar.setBackButtonDrawable(new BackDrawable(false));
    actionBar.setTitle("");
    actionBar.setAllowOverlayTitle(false);
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
        @Override//w w  w . ja va  2 s  . c om
        public void onItemClick(int id) {
            if (id == -1) {
                if (actionBar.isActionModeShowed()) {
                    for (int a = 1; a >= 0; a--) {
                        selectedFiles[a].clear();
                    }
                    cantDeleteMessagesCount = 0;
                    actionBar.hideActionMode();
                    listView.invalidateViews();
                } else {
                    finishFragment();
                }
            } else if (id == shared_media_item) {
                if (selectedMode == 0) {
                    return;
                }
                selectedMode = 0;
                switchToCurrentSelectedMode();
            } else if (id == files_item) {
                if (selectedMode == 1) {
                    return;
                }
                selectedMode = 1;
                switchToCurrentSelectedMode();
            } else if (id == links_item) {
                if (selectedMode == 3) {
                    return;
                }
                selectedMode = 3;
                switchToCurrentSelectedMode();
            } else if (id == music_item) {
                if (selectedMode == 4) {
                    return;
                }
                selectedMode = 4;
                switchToCurrentSelectedMode();
            } else if (id == delete) {
                if (getParentActivity() == null) {
                    return;
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                builder.setMessage(LocaleController.formatString("AreYouSureDeleteMessages",
                        R.string.AreYouSureDeleteMessages, LocaleController.formatPluralString("items",
                                selectedFiles[0].size() + selectedFiles[1].size())));
                builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                builder.setPositiveButton(LocaleController.getString("OK", R.string.OK),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                for (int a = 1; a >= 0; a--) {
                                    ArrayList<Integer> ids = new ArrayList<>(selectedFiles[a].keySet());
                                    ArrayList<Long> random_ids = null;
                                    TLRPC.EncryptedChat currentEncryptedChat = null;
                                    int channelId = 0;
                                    if (!ids.isEmpty()) {
                                        MessageObject msg = selectedFiles[a].get(ids.get(0));
                                        if (channelId == 0 && msg.messageOwner.to_id.channel_id != 0) {
                                            channelId = msg.messageOwner.to_id.channel_id;
                                        }
                                    }
                                    if ((int) dialog_id == 0) {
                                        currentEncryptedChat = MessagesController.getInstance()
                                                .getEncryptedChat((int) (dialog_id >> 32));
                                    }
                                    if (currentEncryptedChat != null) {
                                        random_ids = new ArrayList<>();
                                        for (HashMap.Entry<Integer, MessageObject> entry : selectedFiles[a]
                                                .entrySet()) {
                                            MessageObject msg = entry.getValue();
                                            if (msg.messageOwner.random_id != 0 && msg.type != 10) {
                                                random_ids.add(msg.messageOwner.random_id);
                                            }
                                        }
                                    }
                                    MessagesController.getInstance().deleteMessages(ids, random_ids,
                                            currentEncryptedChat, channelId);
                                    selectedFiles[a].clear();
                                }
                                actionBar.hideActionMode();
                                actionBar.closeSearchField();
                                cantDeleteMessagesCount = 0;
                            }
                        });
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                showDialog(builder.create());
            } else if (id == forward) {
                Bundle args = new Bundle();
                args.putBoolean("onlySelect", true);
                args.putInt("dialogsType", 1);
                DialogsActivity fragment = new DialogsActivity(args);
                fragment.setDelegate(new DialogsActivity.DialogsActivityDelegate() {
                    @Override
                    public void didSelectDialog(DialogsActivity fragment, long did, boolean param) {
                        int lower_part = (int) did;
                        if (lower_part != 0) {
                            Bundle args = new Bundle();
                            args.putBoolean("scrollToTopOnResume", true);
                            if (lower_part > 0) {
                                args.putInt("user_id", lower_part);
                            } else if (lower_part < 0) {
                                args.putInt("chat_id", -lower_part);
                            }
                            if (!MessagesController.checkCanOpenChat(args, fragment)) {
                                return;
                            }

                            ArrayList<MessageObject> fmessages = new ArrayList<>();
                            for (int a = 1; a >= 0; a--) {
                                ArrayList<Integer> ids = new ArrayList<>(selectedFiles[a].keySet());
                                Collections.sort(ids);
                                for (Integer id : ids) {
                                    if (id > 0) {
                                        fmessages.add(selectedFiles[a].get(id));
                                    }
                                }
                                selectedFiles[a].clear();
                            }
                            cantDeleteMessagesCount = 0;
                            actionBar.hideActionMode();

                            NotificationCenter.getInstance()
                                    .postNotificationName(NotificationCenter.closeChats);

                            ChatActivity chatActivity = new ChatActivity(args);
                            presentFragment(chatActivity, true);
                            chatActivity.showReplyPanel(true, null, fmessages, null, false, false);

                            if (!AndroidUtilities.isTablet()) {
                                removeSelfFromStack();
                            }
                        } else {
                            fragment.finishFragment();
                        }
                    }
                });
                presentFragment(fragment);
            }
        }
    });

    for (int a = 1; a >= 0; a--) {
        selectedFiles[a].clear();
    }
    cantDeleteMessagesCount = 0;
    actionModeViews.clear();

    final ActionBarMenu menu = actionBar.createMenu();
    searchItem = menu.addItem(0, R.drawable.ic_ab_search).setIsSearchField(true)
            .setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() {
                @Override
                public void onSearchExpand() {
                    dropDownContainer.setVisibility(View.GONE);
                    searching = true;
                }

                @Override
                public void onSearchCollapse() {
                    dropDownContainer.setVisibility(View.VISIBLE);
                    if (selectedMode == 1) {
                        documentsSearchAdapter.search(null);
                    } else if (selectedMode == 3) {
                        linksSearchAdapter.search(null);
                    } else if (selectedMode == 4) {
                        audioSearchAdapter.search(null);
                    }
                    searching = false;
                    searchWas = false;
                    switchToCurrentSelectedMode();
                }

                @Override
                public void onTextChanged(EditText editText) {
                    String text = editText.getText().toString();
                    if (text.length() != 0) {
                        searchWas = true;
                        switchToCurrentSelectedMode();
                    }
                    if (selectedMode == 1) {
                        if (documentsSearchAdapter == null) {
                            return;
                        }
                        documentsSearchAdapter.search(text);
                    } else if (selectedMode == 3) {
                        if (linksSearchAdapter == null) {
                            return;
                        }
                        linksSearchAdapter.search(text);
                    } else if (selectedMode == 4) {
                        if (audioSearchAdapter == null) {
                            return;
                        }
                        audioSearchAdapter.search(text);
                    }
                }
            });
    searchItem.getSearchField().setHint(LocaleController.getString("Search", R.string.Search));
    searchItem.setVisibility(View.GONE);

    dropDownContainer = new ActionBarMenuItem(context, menu, 0);
    dropDownContainer.setSubMenuOpenSide(1);
    dropDownContainer.addSubItem(shared_media_item,
            LocaleController.getString("SharedMediaTitle", R.string.SharedMediaTitle), 0);
    dropDownContainer.addSubItem(files_item,
            LocaleController.getString("DocumentsTitle", R.string.DocumentsTitle), 0);
    if ((int) dialog_id != 0) {
        dropDownContainer.addSubItem(links_item, LocaleController.getString("LinksTitle", R.string.LinksTitle),
                0);
        dropDownContainer.addSubItem(music_item, LocaleController.getString("AudioTitle", R.string.AudioTitle),
                0);
    } else {
        TLRPC.EncryptedChat currentEncryptedChat = MessagesController.getInstance()
                .getEncryptedChat((int) (dialog_id >> 32));
        if (currentEncryptedChat != null
                && AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 46) {
            dropDownContainer.addSubItem(music_item,
                    LocaleController.getString("AudioTitle", R.string.AudioTitle), 0);
        }
    }
    actionBar.addView(dropDownContainer, 0,
            LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT,
                    Gravity.TOP | Gravity.LEFT, AndroidUtilities.isTablet() ? 64 : 56, 0, 40, 0));
    dropDownContainer.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            dropDownContainer.toggleSubMenu();
        }
    });

    dropDown = new TextView(context);
    dropDown.setGravity(Gravity.LEFT);
    dropDown.setSingleLine(true);
    dropDown.setLines(1);
    dropDown.setMaxLines(1);
    dropDown.setEllipsize(TextUtils.TruncateAt.END);
    dropDown.setTextColor(0xffffffff);
    dropDown.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    dropDown.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_arrow_drop_down, 0);
    dropDown.setCompoundDrawablePadding(AndroidUtilities.dp(4));
    dropDown.setPadding(0, 0, AndroidUtilities.dp(10), 0);
    dropDownContainer.addView(dropDown, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, 16, 0, 0, 0));

    final ActionBarMenu actionMode = actionBar.createActionMode();

    selectedMessagesCountTextView = new NumberTextView(actionMode.getContext());
    selectedMessagesCountTextView.setTextSize(18);
    selectedMessagesCountTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    selectedMessagesCountTextView.setTextColor(0xff737373);
    selectedMessagesCountTextView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return true;
        }
    });
    actionMode.addView(selectedMessagesCountTextView,
            LayoutHelper.createLinear(0, LayoutHelper.MATCH_PARENT, 1.0f, 65, 0, 0, 0));

    if ((int) dialog_id != 0) {
        actionModeViews.add(actionMode.addItem(forward, R.drawable.ic_ab_fwd_forward,
                Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));
    }
    actionModeViews.add(actionMode.addItem(delete, R.drawable.ic_ab_fwd_delete,
            Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));

    photoVideoAdapter = new SharedPhotoVideoAdapter(context);
    documentsAdapter = new SharedDocumentsAdapter(context, 1);
    audioAdapter = new SharedDocumentsAdapter(context, 4);
    documentsSearchAdapter = new MediaSearchAdapter(context, 1);
    audioSearchAdapter = new MediaSearchAdapter(context, 4);
    linksSearchAdapter = new MediaSearchAdapter(context, 3);
    linksAdapter = new SharedLinksAdapter(context);

    FrameLayout frameLayout;
    fragmentView = frameLayout = new FrameLayout(context);

    listView = new SectionsListView(context);
    listView.setDivider(null);
    listView.setDividerHeight(0);
    listView.setDrawSelectorOnTop(true);
    listView.setClipToPadding(false);
    frameLayout.addView(listView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
            if ((selectedMode == 1 || selectedMode == 4) && view instanceof SharedDocumentCell) {
                MediaActivity.this.onItemClick(i, view, ((SharedDocumentCell) view).getMessage(), 0);
            } else if (selectedMode == 3 && view instanceof SharedLinkCell) {
                MediaActivity.this.onItemClick(i, view, ((SharedLinkCell) view).getMessage(), 0);
            }
        }
    });
    listView.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            if (scrollState == SCROLL_STATE_TOUCH_SCROLL && searching && searchWas) {
                AndroidUtilities.hideKeyboard(getParentActivity().getCurrentFocus());
            }
            scrolling = scrollState != SCROLL_STATE_IDLE;
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            if (searching && searchWas) {
                return;
            }
            if (visibleItemCount != 0 && firstVisibleItem + visibleItemCount > totalItemCount - 2
                    && !sharedMediaData[selectedMode].loading) {
                int type;
                if (selectedMode == 0) {
                    type = SharedMediaQuery.MEDIA_PHOTOVIDEO;
                } else if (selectedMode == 1) {
                    type = SharedMediaQuery.MEDIA_FILE;
                } else if (selectedMode == 2) {
                    type = SharedMediaQuery.MEDIA_AUDIO;
                } else if (selectedMode == 4) {
                    type = SharedMediaQuery.MEDIA_MUSIC;
                } else {
                    type = SharedMediaQuery.MEDIA_URL;
                }
                if (!sharedMediaData[selectedMode].endReached[0]) {
                    sharedMediaData[selectedMode].loading = true;
                    SharedMediaQuery.loadMedia(dialog_id, 0, 50, sharedMediaData[selectedMode].max_id[0], type,
                            true, classGuid);
                } else if (mergeDialogId != 0 && !sharedMediaData[selectedMode].endReached[1]) {
                    sharedMediaData[selectedMode].loading = true;
                    SharedMediaQuery.loadMedia(mergeDialogId, 0, 50, sharedMediaData[selectedMode].max_id[1],
                            type, true, classGuid);
                }
            }
        }
    });
    listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int i, long id) {
            if ((selectedMode == 1 || selectedMode == 4) && view instanceof SharedDocumentCell) {
                SharedDocumentCell cell = (SharedDocumentCell) view;
                MessageObject message = cell.getMessage();
                return MediaActivity.this.onItemLongClick(message, view, 0);
            } else if (selectedMode == 3 && view instanceof SharedLinkCell) {
                SharedLinkCell cell = (SharedLinkCell) view;
                MessageObject message = cell.getMessage();
                return MediaActivity.this.onItemLongClick(message, view, 0);
            }
            return false;
        }
    });

    for (int a = 0; a < 6; a++) {
        cellCache.add(new SharedPhotoVideoCell(context));
    }

    emptyView = new LinearLayout(context);
    emptyView.setOrientation(LinearLayout.VERTICAL);
    emptyView.setGravity(Gravity.CENTER);
    emptyView.setVisibility(View.GONE);
    emptyView.setBackgroundColor(0xfff0f0f0);
    frameLayout.addView(emptyView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    emptyView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return true;
        }
    });

    emptyImageView = new ImageView(context);
    emptyView.addView(emptyImageView,
            LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT));

    emptyTextView = new TextView(context);
    emptyTextView.setTextColor(0xff8a8a8a);
    emptyTextView.setGravity(Gravity.CENTER);
    emptyTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17);
    emptyTextView.setPadding(AndroidUtilities.dp(40), 0, AndroidUtilities.dp(40), AndroidUtilities.dp(128));
    emptyView.addView(emptyTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, 24, 0, 0));

    progressView = new LinearLayout(context);
    progressView.setGravity(Gravity.CENTER);
    progressView.setOrientation(LinearLayout.VERTICAL);
    progressView.setVisibility(View.GONE);
    progressView.setBackgroundColor(0xfff0f0f0);
    frameLayout.addView(progressView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));

    ProgressBar progressBar = new ProgressBar(context);
    progressView.addView(progressBar,
            LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT));

    switchToCurrentSelectedMode();

    if (!AndroidUtilities.isTablet()) {
        frameLayout.addView(new PlayerView(context, this), LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
                39, Gravity.TOP | Gravity.LEFT, 0, -36, 0, 0));
    }

    return fragmentView;
}

From source file:kr.wdream.ui.MediaActivity.java

@Override
public View createView(Context context) {
    Log.d(LOG_TAG, "createView");
    actionBar.setBackButtonDrawable(new BackDrawable(false));
    actionBar.setTitle("");
    actionBar.setAllowOverlayTitle(false);
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
        @Override//w ww .j ava 2  s .  co  m
        public void onItemClick(int id) {
            if (id == -1) {
                if (actionBar.isActionModeShowed()) {
                    for (int a = 1; a >= 0; a--) {
                        selectedFiles[a].clear();
                    }
                    cantDeleteMessagesCount = 0;
                    actionBar.hideActionMode();
                    listView.invalidateViews();
                } else {
                    finishFragment();
                }
            } else if (id == shared_media_item) {
                if (selectedMode == 0) {
                    return;
                }
                selectedMode = 0;
                switchToCurrentSelectedMode();
            } else if (id == files_item) {
                if (selectedMode == 1) {
                    return;
                }
                selectedMode = 1;
                switchToCurrentSelectedMode();
            } else if (id == links_item) {
                if (selectedMode == 3) {
                    return;
                }
                selectedMode = 3;
                switchToCurrentSelectedMode();
            } else if (id == music_item) {
                if (selectedMode == 4) {
                    return;
                }
                selectedMode = 4;
                switchToCurrentSelectedMode();
            } else if (id == delete) {
                if (getParentActivity() == null) {
                    return;
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                builder.setMessage(LocaleController.formatString("AreYouSureDeleteMessages",
                        kr.wdream.storyshop.R.string.AreYouSureDeleteMessages,
                        LocaleController.formatPluralString("items",
                                selectedFiles[0].size() + selectedFiles[1].size())));
                builder.setTitle(LocaleController.getString("AppName", kr.wdream.storyshop.R.string.AppName));
                builder.setPositiveButton(LocaleController.getString("OK", kr.wdream.storyshop.R.string.OK),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                for (int a = 1; a >= 0; a--) {
                                    ArrayList<Integer> ids = new ArrayList<>(selectedFiles[a].keySet());
                                    ArrayList<Long> random_ids = null;
                                    TLRPC.EncryptedChat currentEncryptedChat = null;
                                    int channelId = 0;
                                    if (!ids.isEmpty()) {
                                        MessageObject msg = selectedFiles[a].get(ids.get(0));
                                        if (channelId == 0 && msg.messageOwner.to_id.channel_id != 0) {
                                            channelId = msg.messageOwner.to_id.channel_id;
                                        }
                                    }
                                    if ((int) dialog_id == 0) {
                                        currentEncryptedChat = MessagesController.getInstance()
                                                .getEncryptedChat((int) (dialog_id >> 32));
                                    }
                                    if (currentEncryptedChat != null) {
                                        random_ids = new ArrayList<>();
                                        for (HashMap.Entry<Integer, MessageObject> entry : selectedFiles[a]
                                                .entrySet()) {
                                            MessageObject msg = entry.getValue();
                                            if (msg.messageOwner.random_id != 0 && msg.type != 10) {
                                                random_ids.add(msg.messageOwner.random_id);
                                            }
                                        }
                                    }
                                    MessagesController.getInstance().deleteMessages(ids, random_ids,
                                            currentEncryptedChat, channelId);
                                    selectedFiles[a].clear();
                                }
                                actionBar.hideActionMode();
                                actionBar.closeSearchField();
                                cantDeleteMessagesCount = 0;
                            }
                        });
                builder.setNegativeButton(
                        LocaleController.getString("Cancel", kr.wdream.storyshop.R.string.Cancel), null);
                showDialog(builder.create());
            } else if (id == forward) {
                Bundle args = new Bundle();
                args.putBoolean("onlySelect", true);
                args.putInt("dialogsType", 1);
                DialogsActivity fragment = new DialogsActivity(args);
                fragment.setDelegate(new DialogsActivity.DialogsActivityDelegate() {
                    @Override
                    public void didSelectDialog(DialogsActivity fragment, long did, boolean param) {
                        int lower_part = (int) did;
                        if (lower_part != 0) {
                            Bundle args = new Bundle();
                            args.putBoolean("scrollToTopOnResume", true);
                            if (lower_part > 0) {
                                args.putInt("user_id", lower_part);
                            } else if (lower_part < 0) {
                                args.putInt("chat_id", -lower_part);
                            }
                            if (!MessagesController.checkCanOpenChat(args, fragment)) {
                                return;
                            }

                            ArrayList<MessageObject> fmessages = new ArrayList<>();
                            for (int a = 1; a >= 0; a--) {
                                ArrayList<Integer> ids = new ArrayList<>(selectedFiles[a].keySet());
                                Collections.sort(ids);
                                for (Integer id : ids) {
                                    if (id > 0) {
                                        fmessages.add(selectedFiles[a].get(id));
                                    }
                                }
                                selectedFiles[a].clear();
                            }
                            cantDeleteMessagesCount = 0;
                            actionBar.hideActionMode();

                            NotificationCenter.getInstance()
                                    .postNotificationName(NotificationCenter.closeChats);

                            ChatActivity chatActivity = new ChatActivity(args);
                            presentFragment(chatActivity, true);
                            chatActivity.showReplyPanel(true, null, fmessages, null, false, false);

                            if (!AndroidUtilities.isTablet()) {
                                removeSelfFromStack();
                            }
                        } else {
                            fragment.finishFragment();
                        }
                    }
                });
                presentFragment(fragment);
            }
        }
    });

    for (int a = 1; a >= 0; a--) {
        selectedFiles[a].clear();
    }
    cantDeleteMessagesCount = 0;
    actionModeViews.clear();

    final ActionBarMenu menu = actionBar.createMenu();
    searchItem = menu.addItem(0, kr.wdream.storyshop.R.drawable.ic_ab_search).setIsSearchField(true)
            .setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() {
                @Override
                public void onSearchExpand() {
                    dropDownContainer.setVisibility(View.GONE);
                    searching = true;
                }

                @Override
                public void onSearchCollapse() {
                    dropDownContainer.setVisibility(View.VISIBLE);
                    if (selectedMode == 1) {
                        documentsSearchAdapter.search(null);
                    } else if (selectedMode == 3) {
                        linksSearchAdapter.search(null);
                    } else if (selectedMode == 4) {
                        audioSearchAdapter.search(null);
                    }
                    searching = false;
                    searchWas = false;
                    switchToCurrentSelectedMode();
                }

                @Override
                public void onTextChanged(EditText editText) {
                    String text = editText.getText().toString();
                    if (text.length() != 0) {
                        searchWas = true;
                        switchToCurrentSelectedMode();
                    }
                    if (selectedMode == 1) {
                        if (documentsSearchAdapter == null) {
                            return;
                        }
                        documentsSearchAdapter.search(text);
                    } else if (selectedMode == 3) {
                        if (linksSearchAdapter == null) {
                            return;
                        }
                        linksSearchAdapter.search(text);
                    } else if (selectedMode == 4) {
                        if (audioSearchAdapter == null) {
                            return;
                        }
                        audioSearchAdapter.search(text);
                    }
                }
            });
    searchItem.getSearchField()
            .setHint(LocaleController.getString("Search", kr.wdream.storyshop.R.string.Search));
    searchItem.setVisibility(View.GONE);

    dropDownContainer = new ActionBarMenuItem(context, menu, 0);
    dropDownContainer.setSubMenuOpenSide(1);
    dropDownContainer.addSubItem(shared_media_item,
            LocaleController.getString("SharedMediaTitle", kr.wdream.storyshop.R.string.SharedMediaTitle), 0);
    dropDownContainer.addSubItem(files_item,
            LocaleController.getString("DocumentsTitle", kr.wdream.storyshop.R.string.DocumentsTitle), 0);
    if ((int) dialog_id != 0) {
        dropDownContainer.addSubItem(links_item,
                LocaleController.getString("LinksTitle", kr.wdream.storyshop.R.string.LinksTitle), 0);
        dropDownContainer.addSubItem(music_item,
                LocaleController.getString("AudioTitle", kr.wdream.storyshop.R.string.AudioTitle), 0);
    } else {
        TLRPC.EncryptedChat currentEncryptedChat = MessagesController.getInstance()
                .getEncryptedChat((int) (dialog_id >> 32));
        if (currentEncryptedChat != null
                && AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 46) {
            dropDownContainer.addSubItem(music_item,
                    LocaleController.getString("AudioTitle", kr.wdream.storyshop.R.string.AudioTitle), 0);
        }
    }
    actionBar.addView(dropDownContainer, 0,
            LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT,
                    Gravity.TOP | Gravity.LEFT, AndroidUtilities.isTablet() ? 64 : 56, 0, 40, 0));
    dropDownContainer.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            dropDownContainer.toggleSubMenu();
        }
    });

    dropDown = new TextView(context);
    dropDown.setGravity(Gravity.LEFT);
    dropDown.setSingleLine(true);
    dropDown.setLines(1);
    dropDown.setMaxLines(1);
    dropDown.setEllipsize(TextUtils.TruncateAt.END);
    dropDown.setTextColor(0xffffffff);
    dropDown.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    dropDown.setCompoundDrawablesWithIntrinsicBounds(0, 0, kr.wdream.storyshop.R.drawable.ic_arrow_drop_down,
            0);
    dropDown.setCompoundDrawablePadding(AndroidUtilities.dp(4));
    dropDown.setPadding(0, 0, AndroidUtilities.dp(10), 0);
    dropDownContainer.addView(dropDown, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, 16, 0, 0, 0));

    final ActionBarMenu actionMode = actionBar.createActionMode();

    selectedMessagesCountTextView = new NumberTextView(actionMode.getContext());
    selectedMessagesCountTextView.setTextSize(18);
    selectedMessagesCountTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    selectedMessagesCountTextView.setTextColor(0xff737373);
    selectedMessagesCountTextView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return true;
        }
    });
    actionMode.addView(selectedMessagesCountTextView,
            LayoutHelper.createLinear(0, LayoutHelper.MATCH_PARENT, 1.0f, 65, 0, 0, 0));

    if ((int) dialog_id != 0) {
        actionModeViews.add(actionMode.addItem(forward, kr.wdream.storyshop.R.drawable.ic_ab_fwd_forward,
                Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));
    }
    actionModeViews.add(actionMode.addItem(delete, kr.wdream.storyshop.R.drawable.ic_ab_fwd_delete,
            Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));

    photoVideoAdapter = new SharedPhotoVideoAdapter(context);
    documentsAdapter = new SharedDocumentsAdapter(context, 1);
    audioAdapter = new SharedDocumentsAdapter(context, 4);
    documentsSearchAdapter = new MediaSearchAdapter(context, 1);
    audioSearchAdapter = new MediaSearchAdapter(context, 4);
    linksSearchAdapter = new MediaSearchAdapter(context, 3);
    linksAdapter = new SharedLinksAdapter(context);

    FrameLayout frameLayout;
    fragmentView = frameLayout = new FrameLayout(context);

    listView = new SectionsListView(context);
    listView.setDivider(null);
    listView.setDividerHeight(0);
    listView.setDrawSelectorOnTop(true);
    listView.setClipToPadding(false);
    frameLayout.addView(listView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
            if ((selectedMode == 1 || selectedMode == 4) && view instanceof SharedDocumentCell) {
                MediaActivity.this.onItemClick(i, view, ((SharedDocumentCell) view).getMessage(), 0);
            } else if (selectedMode == 3 && view instanceof SharedLinkCell) {
                MediaActivity.this.onItemClick(i, view, ((SharedLinkCell) view).getMessage(), 0);
            }
        }
    });
    listView.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            if (scrollState == SCROLL_STATE_TOUCH_SCROLL && searching && searchWas) {
                AndroidUtilities.hideKeyboard(getParentActivity().getCurrentFocus());
            }
            scrolling = scrollState != SCROLL_STATE_IDLE;
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            if (searching && searchWas) {
                return;
            }
            if (visibleItemCount != 0 && firstVisibleItem + visibleItemCount > totalItemCount - 2
                    && !sharedMediaData[selectedMode].loading) {
                int type;
                if (selectedMode == 0) {
                    type = SharedMediaQuery.MEDIA_PHOTOVIDEO;
                } else if (selectedMode == 1) {
                    type = SharedMediaQuery.MEDIA_FILE;
                } else if (selectedMode == 2) {
                    type = SharedMediaQuery.MEDIA_AUDIO;
                } else if (selectedMode == 4) {
                    type = SharedMediaQuery.MEDIA_MUSIC;
                } else {
                    type = SharedMediaQuery.MEDIA_URL;
                }
                if (!sharedMediaData[selectedMode].endReached[0]) {
                    sharedMediaData[selectedMode].loading = true;
                    SharedMediaQuery.loadMedia(dialog_id, 0, 50, sharedMediaData[selectedMode].max_id[0], type,
                            true, classGuid);
                } else if (mergeDialogId != 0 && !sharedMediaData[selectedMode].endReached[1]) {
                    sharedMediaData[selectedMode].loading = true;
                    SharedMediaQuery.loadMedia(mergeDialogId, 0, 50, sharedMediaData[selectedMode].max_id[1],
                            type, true, classGuid);
                }
            }
        }
    });
    listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int i, long id) {
            if ((selectedMode == 1 || selectedMode == 4) && view instanceof SharedDocumentCell) {
                SharedDocumentCell cell = (SharedDocumentCell) view;
                MessageObject message = cell.getMessage();
                return MediaActivity.this.onItemLongClick(message, view, 0);
            } else if (selectedMode == 3 && view instanceof SharedLinkCell) {
                SharedLinkCell cell = (SharedLinkCell) view;
                MessageObject message = cell.getMessage();
                return MediaActivity.this.onItemLongClick(message, view, 0);
            }
            return false;
        }
    });

    for (int a = 0; a < 6; a++) {
        cellCache.add(new SharedPhotoVideoCell(context));
    }

    emptyView = new LinearLayout(context);
    emptyView.setOrientation(LinearLayout.VERTICAL);
    emptyView.setGravity(Gravity.CENTER);
    emptyView.setVisibility(View.GONE);
    emptyView.setBackgroundColor(0xfff0f0f0);
    frameLayout.addView(emptyView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    emptyView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return true;
        }
    });

    emptyImageView = new ImageView(context);
    emptyView.addView(emptyImageView,
            LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT));

    emptyTextView = new TextView(context);
    emptyTextView.setTextColor(0xff8a8a8a);
    emptyTextView.setGravity(Gravity.CENTER);
    emptyTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17);
    emptyTextView.setPadding(AndroidUtilities.dp(40), 0, AndroidUtilities.dp(40), AndroidUtilities.dp(128));
    emptyView.addView(emptyTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, 24, 0, 0));

    progressView = new LinearLayout(context);
    progressView.setGravity(Gravity.CENTER);
    progressView.setOrientation(LinearLayout.VERTICAL);
    progressView.setVisibility(View.GONE);
    progressView.setBackgroundColor(0xfff0f0f0);
    frameLayout.addView(progressView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));

    ProgressBar progressBar = new ProgressBar(context);
    progressView.addView(progressBar,
            LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT));

    switchToCurrentSelectedMode();

    if (!AndroidUtilities.isTablet()) {
        frameLayout.addView(new PlayerView(context, this), LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
                39, Gravity.TOP | Gravity.LEFT, 0, -36, 0, 0));
    }

    return fragmentView;
}

From source file:com.adarshahd.indianrailinfo.donate.TrainDetails.java

private void createTableLayoutTrainAvailability() {

    if (mPage.contains("SORRY")) {
        TextView textViewTrnDtls = new TextView(mActivity);
        textViewTrnDtls.setText("Not a valid class, Please select a different class and try again.");
        textViewTrnDtls.setTextAppearance(mActivity, android.R.style.TextAppearance_DeviceDefault_Large);
        textViewTrnDtls.setPadding(10, 10, 10, 10);
        textViewTrnDtls.setTextColor(Color.RED);
        mFrameLayout.removeAllViews();//from ww  w .jav a  2s  .  c om
        mFrameLayout.addView(textViewTrnDtls);
        if (mDialog.isShowing()) {
            mDialog.cancel();
        }
        return;
    }

    if (mPage.contains("ISL Of")) {
        TextView textViewTrnDtls = new TextView(mActivity);
        textViewTrnDtls.setText("Station is not in ISL Of the Train. \nPlease modify the source/destination!");
        textViewTrnDtls.setTextAppearance(mActivity, android.R.style.TextAppearance_DeviceDefault_Large);
        textViewTrnDtls.setPadding(10, 10, 10, 10);
        textViewTrnDtls.setTextColor(Color.RED);
        mFrameLayout.removeAllViews();
        mFrameLayout.addView(textViewTrnDtls);
        if (mDialog.isShowing()) {
            mDialog.cancel();
        }
        return;
    }

    if (mPage.contains("ERROR")) {
        TextView textViewTrnDtls = new TextView(mActivity);
        textViewTrnDtls.setText("Your request resulted in an error.\nPlease check!");
        textViewTrnDtls.setTextAppearance(mActivity, android.R.style.TextAppearance_DeviceDefault_Large);
        textViewTrnDtls.setPadding(10, 10, 10, 10);
        textViewTrnDtls.setTextColor(Color.RED);
        mFrameLayout.removeAllViews();
        mFrameLayout.addView(textViewTrnDtls);
        if (mDialog.isShowing()) {
            mDialog.cancel();
        }
        return;
    }

    if (mPage.contains("Network Connectivity")) {
        TextView textViewTrnDtls = new TextView(mActivity);
        textViewTrnDtls.setText("Looks like the server is busy.\nPlease try later!");
        textViewTrnDtls.setTextAppearance(mActivity, android.R.style.TextAppearance_DeviceDefault_Large);
        textViewTrnDtls.setPadding(10, 10, 10, 10);
        textViewTrnDtls.setTextColor(Color.RED);
        mFrameLayout.removeAllViews();
        mFrameLayout.addView(textViewTrnDtls);
        if (mDialog.isShowing()) {
            mDialog.cancel();
        }
        return;
    }

    if (mPage.contains("unavailable")) {
        TextView textViewTrnDtls = new TextView(mActivity);
        textViewTrnDtls.setText(
                "Response from server:\n\nYour request could not be processed now.\nPlease try again later!");
        textViewTrnDtls.setTextAppearance(mActivity, android.R.style.TextAppearance_DeviceDefault_Large);
        textViewTrnDtls.setPadding(10, 10, 10, 10);
        textViewTrnDtls.setTextColor(Color.RED);
        mFrameLayout.removeAllViews();
        mFrameLayout.addView(textViewTrnDtls);
        if (mDialog.isShowing()) {
            mDialog.cancel();
        }
        return;
    }

    if (mDetails == null || !mDetails.getTrainNumber().equals(mTrainNumber)) {
        Iterator iterator = null;
        try {
            iterator = mElements.first().parent().parent().parent().getElementsByTag("tr").iterator();
        } catch (Exception e) {
            Log.i("TrainDetails", mPage);
            e.printStackTrace();
            return;
        }
        mListAv = new ArrayList<List<String>>();
        List<String> list;
        Element tmp;
        tmp = (Element) iterator.next();
        list = new ArrayList<String>();
        list.add(tmp.select("th").get(0).text());
        list.add("Date");
        list.add(tmp.select("th").get(2).text());
        //list.add(tmp.select("th").get(3).text());
        mListAv.add(list);
        while (iterator.hasNext()) {
            tmp = (Element) iterator.next();
            if (!tmp.hasText()) {
                continue;
            }
            list = new ArrayList<String>();
            list.add(tmp.select("td").get(0).text());
            list.add(tmp.select("td").get(1).text());
            list.add(tmp.select("td").get(2).text());
            //list.add(tmp.select("td").get(3).text());
            mListAv.add(list);
        }
        mDetails = new Details(mListAv, TrainEnquiry.AVAILABILITY, mTrainNumber);
    } else {
        mListAv = mDetails.getList();
    }
    mTblLayoutAv = new TableLayout(mActivity);
    TableRow row;
    TextView tv1, tv2, tv3;
    mTblLayoutAv.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));
    for (int i = 0; i < mListAv.size(); i++) {
        row = new TableRow(mActivity);
        tv1 = new TextView(mActivity);
        tv2 = new TextView(mActivity);
        tv3 = new TextView(mActivity);
        //tv4 = new TextView(mActivity);

        tv1.setText("   " + mListAv.get(i).get(0));
        tv2.setText("   " + mListAv.get(i).get(1));
        tv3.setText("   " + mListAv.get(i).get(2));
        //tv4.setText("   " + mListAv.get(i).get(3));

        tv1.setTextAppearance(mActivity, android.R.style.TextAppearance_DeviceDefault_Medium);
        tv2.setTextAppearance(mActivity, android.R.style.TextAppearance_DeviceDefault_Medium);
        tv3.setTextAppearance(mActivity, android.R.style.TextAppearance_DeviceDefault_Medium);
        //tv4.setTextAppearance(mActivity,android.R.style.TextAppearance_DeviceDefault_Medium);

        tv1.setPadding(5, 5, 5, 5);
        tv2.setPadding(5, 5, 5, 5);
        tv3.setPadding(5, 5, 5, 5);
        //tv4.setPadding(5,5,5,5);

        /*tv2.setBackgroundResource(R.drawable.card_divider);
        tv3.setBackgroundResource(R.drawable.card_divider);
        tv4.setBackgroundResource(R.drawable.card_divider);*/

        row.addView(tv1);
        row.addView(tv2);
        row.addView(tv3);
        //row.addView(tv4);

        row.setBackgroundResource(R.drawable.button_selector);
        row.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
        row.setOnClickListener(this);
        mTblLayoutAv.addView(row);
    }
    LinearLayout ll = new LinearLayout(mActivity);
    ScrollView scrollView = new ScrollView(mActivity);
    TextView textViewTrnDtls = new TextView(mActivity);
    textViewTrnDtls.setText("Availability details:");
    textViewTrnDtls.setTextAppearance(mActivity, android.R.style.TextAppearance_DeviceDefault_Large);
    textViewTrnDtls.setPadding(10, 10, 10, 10);
    ll.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT));
    ll.setOrientation(LinearLayout.VERTICAL);
    ll.addView(textViewTrnDtls);
    ll.addView(mTblLayoutAv);
    scrollView.addView(ll);
    mFrameLayout.removeAllViews();
    mFrameLayout.addView(scrollView);
    if (mDialog.isShowing()) {
        mDialog.cancel();
    }
}

From source file:com.nickandjerry.dynamiclayoutinflator.DynamicLayoutInflator.java

public static void createViewRunnables() {
    viewRunnables = new HashMap<>(30);
    viewRunnables.put("scaleType", new ViewParamRunnable() {
        @Override//from   w  w w. jav  a2s  .c  o  m
        public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) {
            if (view instanceof ImageView) {
                ImageView.ScaleType scaleType = ((ImageView) view).getScaleType();
                switch (value.toLowerCase()) {
                case "center":
                    scaleType = ImageView.ScaleType.CENTER;
                    break;
                case "center_crop":
                    scaleType = ImageView.ScaleType.CENTER_CROP;
                    break;
                case "center_inside":
                    scaleType = ImageView.ScaleType.CENTER_INSIDE;
                    break;
                case "fit_center":
                    scaleType = ImageView.ScaleType.FIT_CENTER;
                    break;
                case "fit_end":
                    scaleType = ImageView.ScaleType.FIT_END;
                    break;
                case "fit_start":
                    scaleType = ImageView.ScaleType.FIT_START;
                    break;
                case "fit_xy":
                    scaleType = ImageView.ScaleType.FIT_XY;
                    break;
                case "matrix":
                    scaleType = ImageView.ScaleType.MATRIX;
                    break;
                }
                ((ImageView) view).setScaleType(scaleType);
            }
        }
    });
    viewRunnables.put("orientation", new ViewParamRunnable() {
        @Override
        public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) {
            if (view instanceof LinearLayout) {
                ((LinearLayout) view).setOrientation(
                        value.equals("vertical") ? LinearLayout.VERTICAL : LinearLayout.HORIZONTAL);
            }
        }
    });
    viewRunnables.put("text", new ViewParamRunnable() {
        @Override
        public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) {
            if (view instanceof TextView) {
                ((TextView) view).setText(value);
            }
        }
    });
    viewRunnables.put("textSize", new ViewParamRunnable() {
        @Override
        public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) {
            if (view instanceof TextView) {
                ((TextView) view).setTextSize(TypedValue.COMPLEX_UNIT_PX,
                        DimensionConverter.stringToDimension(value, view.getResources().getDisplayMetrics()));
            }
        }
    });
    viewRunnables.put("textColor", new ViewParamRunnable() {
        @Override
        public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) {
            if (view instanceof TextView) {
                ((TextView) view).setTextColor(parseColor(view, value));
            }
        }
    });
    viewRunnables.put("textStyle", new ViewParamRunnable() {
        @Override
        public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) {
            if (view instanceof TextView) {
                int typeFace = Typeface.NORMAL;
                if (value.contains("bold"))
                    typeFace |= Typeface.BOLD;
                else if (value.contains("italic"))
                    typeFace |= Typeface.ITALIC;
                ((TextView) view).setTypeface(null, typeFace);
            }
        }
    });
    viewRunnables.put("textAlignment", new ViewParamRunnable() {
        @Override
        public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
                int alignment = View.TEXT_ALIGNMENT_TEXT_START;
                switch (value) {
                case "center":
                    alignment = View.TEXT_ALIGNMENT_CENTER;
                    break;
                case "left":
                case "textStart":
                    break;
                case "right":
                case "textEnd":
                    alignment = View.TEXT_ALIGNMENT_TEXT_END;
                    break;
                }
                view.setTextAlignment(alignment);
            } else {
                int gravity = Gravity.LEFT;
                switch (value) {
                case "center":
                    gravity = Gravity.CENTER;
                    break;
                case "left":
                case "textStart":
                    break;
                case "right":
                case "textEnd":
                    gravity = Gravity.RIGHT;
                    break;
                }
                ((TextView) view).setGravity(gravity);
            }
        }
    });
    viewRunnables.put("ellipsize", new ViewParamRunnable() {
        @Override
        public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) {
            if (view instanceof TextView) {
                TextUtils.TruncateAt where = TextUtils.TruncateAt.END;
                switch (value) {
                case "start":
                    where = TextUtils.TruncateAt.START;
                    break;
                case "middle":
                    where = TextUtils.TruncateAt.MIDDLE;
                    break;
                case "marquee":
                    where = TextUtils.TruncateAt.MARQUEE;
                    break;
                case "end":
                    break;
                }
                ((TextView) view).setEllipsize(where);
            }
        }
    });
    viewRunnables.put("singleLine", new ViewParamRunnable() {
        @Override
        public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) {
            if (view instanceof TextView) {
                ((TextView) view).setSingleLine();
            }
        }
    });
    viewRunnables.put("hint", new ViewParamRunnable() {
        @Override
        public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) {
            if (view instanceof EditText) {
                ((EditText) view).setHint(value);
            }
        }
    });
    viewRunnables.put("inputType", new ViewParamRunnable() {
        @Override
        public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) {
            if (view instanceof TextView) {
                int inputType = 0;
                switch (value) {
                case "textEmailAddress":
                    inputType |= InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS;
                    break;
                case "number":
                    inputType |= InputType.TYPE_CLASS_NUMBER;
                    break;
                case "phone":
                    inputType |= InputType.TYPE_CLASS_PHONE;
                    break;
                }
                if (inputType > 0)
                    ((TextView) view).setInputType(inputType);
            }
        }
    });
    viewRunnables.put("gravity", new ViewParamRunnable() {
        @Override
        public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) {
            int gravity = parseGravity(value);
            if (view instanceof TextView) {
                ((TextView) view).setGravity(gravity);
            } else if (view instanceof LinearLayout) {
                ((LinearLayout) view).setGravity(gravity);
            } else if (view instanceof RelativeLayout) {
                ((RelativeLayout) view).setGravity(gravity);
            }
        }
    });
    viewRunnables.put("src", new ViewParamRunnable() {
        @Override
        public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) {
            if (view instanceof ImageView) {
                String imageName = value;
                if (imageName.startsWith("//"))
                    imageName = "http:" + imageName;
                if (imageName.startsWith("http")) {
                    if (imageLoader != null) {
                        if (attrs.containsKey("cornerRadius")) {
                            int radius = DimensionConverter.stringToDimensionPixelSize(
                                    attrs.get("cornerRadius"), view.getResources().getDisplayMetrics());
                            imageLoader.loadRoundedImage((ImageView) view, imageName, radius);
                        } else {
                            imageLoader.loadImage((ImageView) view, imageName);
                        }
                    }
                } else if (imageName.startsWith("@drawable/")) {
                    imageName = imageName.substring("@drawable/".length());
                    ((ImageView) view).setImageDrawable(getDrawableByName(view, imageName));
                }
            }
        }
    });
    viewRunnables.put("visibility", new ViewParamRunnable() {
        @Override
        public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) {
            int visibility = View.VISIBLE;
            String visValue = value.toLowerCase();
            if (visValue.equals("gone"))
                visibility = View.GONE;
            else if (visValue.equals("invisible"))
                visibility = View.INVISIBLE;
            view.setVisibility(visibility);
        }
    });
    viewRunnables.put("clickable", new ViewParamRunnable() {
        @Override
        public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) {
            view.setClickable(value.equals("true"));
        }
    });
    viewRunnables.put("tag", new ViewParamRunnable() {
        @Override
        public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) {
            // Sigh, this is dangerous because we use tags for other purposes
            if (view.getTag() == null)
                view.setTag(value);
        }
    });
    viewRunnables.put("onClick", new ViewParamRunnable() {
        @Override
        public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) {
            view.setOnClickListener(getClickListener(parent, value));
        }
    });
}

From source file:foam.opensauces.StarwispBuilder.java

public void Build(final StarwispActivity ctx, final String ctxname, JSONArray arr, ViewGroup parent) {

    try {//from  w  w  w  .j  a  va  2 s .c o  m
        String type = arr.getString(0);

        //Log.i("starwisp","building started "+type);

        if (type.equals("build-fragment")) {
            String name = arr.getString(1);
            int ID = arr.getInt(2);
            Fragment fragment = ActivityManager.GetFragment(name);
            LinearLayout inner = new LinearLayout(ctx);
            inner.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            inner.setId(ID);
            FragmentTransaction fragmentTransaction = ctx.getSupportFragmentManager().beginTransaction();
            fragmentTransaction.add(ID, fragment);
            fragmentTransaction.commit();
            parent.addView(inner);
            return;
        }

        if (type.equals("linear-layout")) {
            LinearLayout v = new LinearLayout(ctx);
            v.setId(arr.getInt(1));
            v.setOrientation(BuildOrientation(arr.getString(2)));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            //v.setPadding(2,2,2,2);
            JSONArray col = arr.getJSONArray(4);
            v.setBackgroundColor(Color.argb(col.getInt(3), col.getInt(0), col.getInt(1), col.getInt(2)));
            parent.addView(v);
            JSONArray children = arr.getJSONArray(5);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }
            return;
        }

        if (type.equals("draggable")) {
            final LinearLayout v = new LinearLayout(ctx);
            final int id = arr.getInt(1);
            v.setPadding(20, 20, 20, 20);
            v.setId(id);
            v.setOrientation(BuildOrientation(arr.getString(2)));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            v.setClickable(true);
            v.setFocusable(true);

            JSONArray col = arr.getJSONArray(4);
            v.setBackgroundResource(R.drawable.draggable);

            GradientDrawable drawable = (GradientDrawable) v.getBackground();
            final int colour = Color.argb(col.getInt(3), col.getInt(0), col.getInt(1), col.getInt(2));
            drawable.setColor(colour);

            parent.addView(v);
            JSONArray children = arr.getJSONArray(5);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }

            // Sets a long click listener for the ImageView using an anonymous listener object that
            // implements the OnLongClickListener interface
            /*                v.setOnLongClickListener(new View.OnLongClickListener() {
            public boolean onLongClick(View vv) {
                if (id!=99) {
                    ClipData dragData = ClipData.newPlainText("simple text", ""+id);
                    View.DragShadowBuilder myShadow = new MyDragShadowBuilder(v);
                    Log.i("starwisp","start drag id "+vv.getId());
                    v.startDrag(dragData, myShadow, null, 0);
                    v.setVisibility(View.GONE);
                    return true;
                }
                return false;
            }
                            });
            */
            // Sets a long click listener for the ImageView using an anonymous listener object that
            // implements the OnLongClickListener interface
            v.setOnTouchListener(new View.OnTouchListener() {
                public boolean onTouch(View vv, MotionEvent event) {
                    if (event.getAction() == MotionEvent.ACTION_DOWN && id != 99) {
                        //                            ClipData dragData = ClipData.newPlainText("simple text", ""+id);

                        ClipData dragData = new ClipData(
                                new ClipDescription(null, new String[] { ClipDescription.MIMETYPE_TEXT_PLAIN }),
                                new ClipData.Item("" + id));

                        View.DragShadowBuilder myShadow = new MyDragShadowBuilder(v);
                        Log.i("starwisp", "start drag id " + vv.getId());
                        v.startDrag(dragData, myShadow, null, 0);
                        v.setVisibility(View.GONE);
                        return true;
                    }
                    return false;
                }
            });

            v.setOnDragListener(new View.OnDragListener() {
                public boolean onDrag(View vv, DragEvent event) {
                    final int action = event.getAction();
                    switch (action) {
                    case DragEvent.ACTION_DRAG_STARTED:
                        if (event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
                            // returns true to indicate that the View can accept the dragged data.
                            return true;
                        } else {
                            // Returns false. During the current drag and drop operation, this View will
                            // not receive events again until ACTION_DRAG_ENDED is sent.
                            return false;
                        }
                    case DragEvent.ACTION_DRAG_ENTERED: {
                        return true;
                    }
                    case DragEvent.ACTION_DRAG_LOCATION:
                        return true;
                    case DragEvent.ACTION_DRAG_EXITED: {
                        return true;
                    }
                    case DragEvent.ACTION_DROP: {
                        ClipData.Item item = event.getClipData().getItemAt(0);
                        String dragData = item.getText().toString();
                        Log.i("starwisp", "Dragged view is " + dragData);
                        int otherid = Integer.parseInt(dragData);
                        View otherw = ctx.findViewById(otherid);
                        Log.i("starwisp", "removing from parent " + ((View) otherw.getParent()).getId());

                        // check we are not adding to ourself
                        if (id != otherid) {
                            ((ViewManager) otherw.getParent()).removeView(otherw);
                            Log.i("starwisp", "adding to " + id);
                            v.addView(otherw);
                        }
                        otherw.setVisibility(View.VISIBLE);
                        return true;
                    }
                    case DragEvent.ACTION_DRAG_ENDED: {
                        if (event.getResult()) {
                        } else {
                        }
                        ;
                        return true;
                    }
                    // An unknown action type was received.
                    default:
                        Log.e("starwisp", "Unknown action type received by OnDragListener.");
                        break;
                    }
                    ;
                    return true;
                }
            });
            return;
        }

        if (type.equals("frame-layout")) {
            FrameLayout v = new FrameLayout(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            parent.addView(v);
            JSONArray children = arr.getJSONArray(3);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }
            return;
        }

        /*
        if (type.equals("grid-layout")) {
        GridLayout v = new GridLayout(ctx);
        v.setId(arr.getInt(1));
        v.setRowCount(arr.getInt(2));
        //v.setColumnCount(arr.getInt(2));
        v.setOrientation(BuildOrientation(arr.getString(3)));
        v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
                
        parent.addView(v);
        JSONArray children = arr.getJSONArray(5);
        for (int i=0; i<children.length(); i++) {
            Build(ctx,ctxname,new JSONArray(children.getString(i)), v);
        }
                
        return;
        }
        */

        if (type.equals("scroll-view")) {
            HorizontalScrollView v = new HorizontalScrollView(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            parent.addView(v);
            JSONArray children = arr.getJSONArray(3);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }
            return;
        }

        if (type.equals("scroll-view-vert")) {
            ScrollView v = new ScrollView(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            parent.addView(v);
            JSONArray children = arr.getJSONArray(3);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }
            return;
        }

        if (type.equals("view-pager")) {
            ViewPager v = new ViewPager(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            v.setOffscreenPageLimit(3);
            final JSONArray items = arr.getJSONArray(3);

            v.setAdapter(new FragmentPagerAdapter(ctx.getSupportFragmentManager()) {

                @Override
                public int getCount() {
                    return items.length();
                }

                @Override
                public Fragment getItem(int position) {
                    try {
                        String fragname = items.getString(position);
                        return ActivityManager.GetFragment(fragname);
                    } catch (JSONException e) {
                        Log.e("starwisp", "Error parsing data " + e.toString());
                    }
                    return null;
                }
            });
            parent.addView(v);
            return;
        }

        if (type.equals("space")) {
            // Space v = new Space(ctx); (class not found runtime error??)
            TextView v = new TextView(ctx);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            parent.addView(v);
        }

        if (type.equals("image-view")) {
            ImageView v = new ImageView(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));

            String image = arr.getString(2);

            if (image.startsWith("/")) {
                Bitmap bitmap = BitmapFactory.decodeFile(image);
                v.setImageBitmap(bitmap);
            } else {
                int id = ctx.getResources().getIdentifier(image, "drawable", ctx.getPackageName());
                v.setImageResource(id);
            }

            parent.addView(v);
        }

        if (type.equals("text-view")) {
            TextView v = new TextView(ctx);
            v.setId(arr.getInt(1));
            v.setText(Html.fromHtml(arr.getString(2)));
            v.setTextSize(arr.getInt(3));
            v.setMovementMethod(LinkMovementMethod.getInstance());
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
            v.setClickable(false);
            v.setEnabled(false);

            v.setOnTouchListener(new View.OnTouchListener() {
                public boolean onTouch(View vv, MotionEvent event) {
                    return false;
                }
            });

            if (arr.length() > 5) {
                if (arr.getString(5).equals("left")) {
                    v.setGravity(Gravity.LEFT);
                } else {
                    if (arr.getString(5).equals("fill")) {
                        v.setGravity(Gravity.FILL);
                    } else {
                        v.setGravity(Gravity.CENTER);
                    }
                }
            } else {
                v.setGravity(Gravity.LEFT);
            }
            v.setTypeface(((StarwispActivity) ctx).m_Typeface);
            parent.addView(v);
        }

        if (type.equals("debug-text-view")) {
            TextView v = (TextView) ctx.getLayoutInflater().inflate(R.layout.debug_text, null);
            //                v.setBackgroundResource(R.color.black);
            v.setId(arr.getInt(1));
            //                v.setText(Html.fromHtml(arr.getString(2)));
            //                v.setTextColor(R.color.white);
            //                v.setTextSize(arr.getInt(3));
            //                v.setMovementMethod(LinkMovementMethod.getInstance());
            //                v.setMaxLines(10);
            //                v.setVerticalScrollBarEnabled(true);
            //                v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
            //v.setMovementMethod(new ScrollingMovementMethod());

            /*
            if (arr.length()>5) {
            if (arr.getString(5).equals("left")) {
                v.setGravity(Gravity.LEFT);
            } else {
                if (arr.getString(5).equals("fill")) {
                    v.setGravity(Gravity.FILL);
                } else {
                    v.setGravity(Gravity.CENTER);
                }
            }
            } else {
            v.setGravity(Gravity.LEFT);
            }
            v.setTypeface(((StarwispActivity)ctx).m_Typeface);*/
            parent.addView(v);
        }

        if (type.equals("web-view")) {
            WebView v = new WebView(ctx);
            v.setId(arr.getInt(1));
            v.setVerticalScrollBarEnabled(false);
            v.loadData(arr.getString(2), "text/html", "utf-8");
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            parent.addView(v);
        }

        if (type.equals("edit-text")) {
            final EditText v = new EditText(ctx);
            v.setId(arr.getInt(1));
            v.setText(arr.getString(2));
            v.setTextSize(arr.getInt(3));

            String inputtype = arr.getString(4);
            if (inputtype.equals("text")) {
                //v.setInputType(InputType.TYPE_CLASS_TEXT);
            } else if (inputtype.equals("numeric")) {
                v.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
            } else if (inputtype.equals("email")) {
                v.setInputType(InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS);
            }

            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(5)));
            v.setTypeface(((StarwispActivity) ctx).m_Typeface);
            final String fn = arr.getString(5);
            //v.setSingleLine(true);

            v.addTextChangedListener(new TextWatcher() {
                public void afterTextChanged(Editable s) {
                    CallbackArgs(ctx, ctxname, v.getId(), "\"" + s.toString() + "\"");
                }

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

                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }
            });

            parent.addView(v);
        }

        if (type.equals("button")) {
            Button v = new Button(ctx);
            v.setId(arr.getInt(1));
            v.setText(arr.getString(2));
            v.setTextSize(arr.getInt(3));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
            v.setTypeface(((StarwispActivity) ctx).m_Typeface);
            final String fn = arr.getString(5);
            v.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    Callback(ctx, ctxname, v.getId());
                }
            });

            parent.addView(v);
        }

        if (type.equals("toggle-button")) {
            ToggleButton v = new ToggleButton(ctx);
            if (arr.getString(5).equals("fancy")) {
                v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_fancy, null);
            }

            if (arr.getString(5).equals("yes")) {
                v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_yes, null);
            }

            if (arr.getString(5).equals("maybe")) {
                v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_maybe, null);
            }

            if (arr.getString(5).equals("no")) {
                v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_no, null);
            }

            v.setId(arr.getInt(1));
            v.setText(arr.getString(2));
            v.setTextSize(arr.getInt(3));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
            v.setTypeface(((StarwispActivity) ctx).m_Typeface);
            final String fn = arr.getString(6);
            v.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    String arg = "#f";
                    if (((ToggleButton) v).isChecked())
                        arg = "#t";
                    CallbackArgs(ctx, ctxname, v.getId(), arg);
                }
            });
            parent.addView(v);
        }

        if (type.equals("seek-bar")) {
            SeekBar v = new SeekBar(ctx);
            v.setId(arr.getInt(1));
            v.setMax(arr.getInt(2));
            v.setProgress(arr.getInt(2) / 2);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            final String fn = arr.getString(4);

            v.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                public void onProgressChanged(SeekBar v, int a, boolean s) {
                    CallbackArgs(ctx, ctxname, v.getId(), Integer.toString(a));
                }

                public void onStartTrackingTouch(SeekBar v) {
                }

                public void onStopTrackingTouch(SeekBar v) {
                }
            });
            parent.addView(v);
        }

        if (type.equals("spinner")) {
            Spinner v = new Spinner(ctx);
            final int wid = arr.getInt(1);
            v.setId(wid);
            final JSONArray items = arr.getJSONArray(2);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            ArrayList<String> spinnerArray = new ArrayList<String>();

            for (int i = 0; i < items.length(); i++) {
                spinnerArray.add(items.getString(i));
            }

            ArrayAdapter spinnerArrayAdapter = new ArrayAdapter<String>(ctx, R.layout.spinner_item,
                    spinnerArray) {
                public View getView(int position, View convertView, ViewGroup parent) {
                    View v = super.getView(position, convertView, parent);
                    ((TextView) v).setTypeface(((StarwispActivity) ctx).m_Typeface);
                    return v;
                }
            };

            spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_layout);

            v.setAdapter(spinnerArrayAdapter);
            v.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                public void onItemSelected(AdapterView<?> a, View v, int pos, long id) {
                    try {
                        CallbackArgs(ctx, ctxname, wid, "\"" + items.getString(pos) + "\"");
                    } catch (JSONException e) {
                        Log.e("starwisp", "Error parsing data " + e.toString());
                    }
                }

                public void onNothingSelected(AdapterView<?> v) {
                }
            });

            parent.addView(v);
        }

        if (type.equals("canvas")) {
            StarwispCanvas v = new StarwispCanvas(ctx);
            final int wid = arr.getInt(1);
            v.setId(wid);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            v.SetDrawList(arr.getJSONArray(3));
            parent.addView(v);
        }

        if (type.equals("camera-preview")) {
            PictureTaker pt = new PictureTaker();
            CameraPreview v = new CameraPreview(ctx, pt);
            final int wid = arr.getInt(1);
            v.setId(wid);

            //              LinearLayout.LayoutParams lp =
            //  new LinearLayout.LayoutParams(minWidth, minHeight, 1);

            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));

            //                v.setLayoutParams(lp);
            parent.addView(v);
        }

        if (type.equals("button-grid")) {
            LinearLayout horiz = new LinearLayout(ctx);
            final int id = arr.getInt(1);
            final String buttontype = arr.getString(2);
            horiz.setId(id);
            horiz.setOrientation(LinearLayout.HORIZONTAL);
            parent.addView(horiz);
            int height = arr.getInt(3);
            int textsize = arr.getInt(4);
            LinearLayout.LayoutParams lp = BuildLayoutParams(arr.getJSONArray(5));
            JSONArray buttons = arr.getJSONArray(6);
            int count = buttons.length();
            int vertcount = 0;
            LinearLayout vert = null;

            for (int i = 0; i < count; i++) {
                JSONArray button = buttons.getJSONArray(i);

                if (vertcount == 0) {
                    vert = new LinearLayout(ctx);
                    vert.setId(0);
                    vert.setOrientation(LinearLayout.VERTICAL);
                    horiz.addView(vert);
                }
                vertcount = (vertcount + 1) % height;

                if (buttontype.equals("button")) {
                    Button b = new Button(ctx);
                    b.setId(button.getInt(0));
                    b.setText(button.getString(1));
                    b.setTextSize(textsize);
                    b.setLayoutParams(lp);
                    b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                    final String fn = arr.getString(6);
                    b.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            CallbackArgs(ctx, ctxname, id, "" + v.getId() + " #t");
                        }
                    });
                    vert.addView(b);
                } else if (buttontype.equals("toggle")) {
                    ToggleButton b = new ToggleButton(ctx);
                    b.setId(button.getInt(0));
                    b.setText(button.getString(1));
                    b.setTextSize(textsize);
                    b.setLayoutParams(lp);
                    b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                    final String fn = arr.getString(6);
                    b.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            String arg = "#f";
                            if (((ToggleButton) v).isChecked())
                                arg = "#t";
                            CallbackArgs(ctx, ctxname, id, "" + v.getId() + " " + arg);
                        }
                    });
                    vert.addView(b);
                }
            }
        }

    } catch (JSONException e) {
        Log.e("starwisp", "Error parsing [" + arr.toString() + "] " + e.toString());
    }

    //Log.i("starwisp","building ended");

}

From source file:com.nbplus.vbroadlauncher.fragment.LauncherFragment.java

private void setContentViewByOrientation() {
    int orientation = DisplayUtils.getScreenOrientation(getActivity());
    LinearLayout.LayoutParams lp;/*  w w  w  . jav a  2  s  .  com*/
    float marginDp = 0f;
    float marginPx = 0f;

    if (orientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
            || orientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE) {
        mMainViewLayout.setOrientation(LinearLayout.HORIZONTAL);

        lp = (LinearLayout.LayoutParams) mMainViewLeftPanel.getLayoutParams();
        lp.weight = 0.6f;
        marginDp = DisplayUtils.getDimension(getActivity(), R.dimen.launcher_panel_margin);
        marginPx = DisplayUtils.pxFromDp(getActivity(), marginDp);
        lp.setMargins(0, 0, (int) marginPx, 0);
        mMainViewLeftPanel.setLayoutParams(lp);
        lp = (LinearLayout.LayoutParams) mMainViewRightPanel.getLayoutParams();
        lp.weight = 0.4f;
        lp.setMargins(0, 0, 0, 0);
        mMainViewRightPanel.setLayoutParams(lp);
    } else {
        mMainViewLayout.setOrientation(LinearLayout.VERTICAL);

        lp = (LinearLayout.LayoutParams) mMainViewLeftPanel.getLayoutParams();
        lp.weight = 1.0f;
        marginDp = DisplayUtils.getDimension(getActivity(), R.dimen.launcher_panel_margin);
        marginPx = DisplayUtils.pxFromDp(getActivity(), marginDp);
        lp.setMargins(0, 0, 0, (int) marginPx);
        mMainViewLeftPanel.setLayoutParams(lp);
        lp = (LinearLayout.LayoutParams) mMainViewRightPanel.getLayoutParams();
        lp.weight = 1.0f;
        lp.setMargins(0, 0, 0, 0);
        mMainViewRightPanel.setLayoutParams(lp);
    }
    lp = (LinearLayout.LayoutParams) mMainViewLayout.getLayoutParams();

    float heightDp = DisplayUtils.getDimension(getActivity(), R.dimen.launcher_main_view_margin_top);
    float px = DisplayUtils.pxFromDp(getActivity(), heightDp);
    float horizontalMarginDp = DisplayUtils.getDimension(getActivity(),
            R.dimen.launcher_main_view_margin_horizontal);
    float horizontalMarginPx = DisplayUtils.pxFromDp(getActivity(), horizontalMarginDp);

    lp.setMargins((int) horizontalMarginPx, (int) px, (int) horizontalMarginPx, lp.bottomMargin);
    mMainViewLayout.setLayoutParams(lp);

    float dp = DisplayUtils.getDimension(getActivity(), R.dimen.launcher_clock_height);
    px = DisplayUtils.pxFromDp(getActivity(), dp);
    mTextClock.setTextSize(px);
    mWeatherView.onConfigurationChanged(orientation);

    // right shortcut menu
    dp = DisplayUtils.getDimension(getActivity(), R.dimen.launcher_ic_menu_main_shortcut_width);
    float widthPx = DisplayUtils.pxFromDp(getActivity(), dp);

    dp = DisplayUtils.getDimension(getActivity(), R.dimen.launcher_ic_menu_main_shortcut_height);
    float heightPx = DisplayUtils.pxFromDp(getActivity(), dp);

    dp = DisplayUtils.getDimension(getActivity(), R.dimen.launcher_ic_menu_main_shortcut_font_size);
    float mainShortcutFontPx = DisplayUtils.pxFromDp(getActivity(), dp);

    GridLayout.LayoutParams childlp;
    View child;
    for (int i = 0; i < mMainShortcutGridLayout.getChildCount(); i++) {
        /**
         * right shortcut panel
         */
        child = mMainShortcutGridLayout.getChildAt(i);

        childlp = (GridLayout.LayoutParams) child.getLayoutParams();
        childlp.width = (int) widthPx;
        childlp.height = (int) heightPx;
        child.setLayoutParams(childlp);
    }

    // add other shortcuts.
    dp = DisplayUtils.getDimension(getActivity(), R.dimen.launcher_ic_menu_shortcut_width);
    float btnWidthPx = DisplayUtils.pxFromDp(getActivity(), dp);
    dp = DisplayUtils.getDimension(getActivity(), R.dimen.launcher_ic_menu_shortcut_height);
    float btnHeightPx = DisplayUtils.pxFromDp(getActivity(), dp);

    dp = DisplayUtils.getDimension(getActivity(), R.dimen.ic_nav_btn_drawable_padding);
    float drawablePadding = DisplayUtils.pxFromDp(getActivity(), dp);

    dp = DisplayUtils.getDimension(getActivity(), R.dimen.launcher_ic_menu_shortcut_font_size);
    float btnFontPx = DisplayUtils.pxFromDp(getActivity(), dp);

    for (int i = 0; i < mShorcutGridLayout.getChildCount(); i++) {
        /**
         * right shortcut panel
         */
        child = mShorcutGridLayout.getChildAt(i);

        childlp = (GridLayout.LayoutParams) child.getLayoutParams();
        childlp.width = (int) btnWidthPx;
        childlp.height = (int) btnHeightPx;
        child.setLayoutParams(childlp);
    }
}