Example usage for android.widget ListView ListView

List of usage examples for android.widget ListView ListView

Introduction

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

Prototype

public ListView(Context context) 

Source Link

Usage

From source file:de.mkrtchyan.recoverytools.FlashFragment.java

public void showFlashHistory() {
    final ArrayList<File> HistoryFiles = new ArrayList<>();
    final ArrayList<String> HistoryFileNames = new ArrayList<>();
    final AppCompatDialog HistoryDialog = new AppCompatDialog(mContext);
    HistoryDialog.setTitle(R.string.history);
    ListView HistoryList = new ListView(mContext);
    File tmp;// ww  w.jav  a2s .  co m
    for (int i = 0; i < 5; i++) {
        tmp = new File(Common.getStringPref(mContext, Constants.PREF_NAME,
                Constants.PREF_KEY_HISTORY + String.valueOf(i)));
        if (tmp.exists() && !tmp.isDirectory()) {
            HistoryFiles.add(tmp);
            HistoryFileNames.add(tmp.getName());
        } else {
            Common.setStringPref(mContext, Constants.PREF_NAME, Constants.PREF_KEY_HISTORY + String.valueOf(i),
                    "");
        }
    }
    HistoryList.setAdapter(new ArrayAdapter<>(mContext, android.R.layout.simple_list_item_1, HistoryFileNames));
    HistoryList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

            if (HistoryFiles.get(arg2).exists()) {
                mActivity.switchTo(FlashAsFragment.newInstance(mActivity, HistoryFiles.get(arg2), true));
                HistoryDialog.dismiss();
            }
        }
    });
    HistoryDialog.setContentView(HistoryList);
    if (HistoryFileNames.toArray().length > 0) {
        HistoryDialog.show();
    } else {
        Toast.makeText(mActivity, R.string.no_history, Toast.LENGTH_SHORT).show();
    }
}

From source file:org.solovyev.android.messenger.BaseListFragment.java

@Nonnull
private View createListView(@Nonnull Context context) {
    final View listView = new ListView(context);
    fillListView((ListView) listView, context);
    listView.setId(android.R.id.list);//from w w w .j a  v a  2 s. co  m
    return listView;
}

From source file:odoo.controls.OSelectionField.java

private AlertDialog createSelectionDialog(final int selected_position, final List<ODataRow> items,
        LayoutParams params) {/* w w  w  .jav a2 s .c  o  m*/
    final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
    ListView dialogView = new ListView(mContext);
    dialogView.setAdapter(mAdapter);
    dialogView.setOnItemClickListener(this);
    dialogView.setLayoutParams(params);
    builder.setView(dialogView);
    return builder.create();
}

From source file:org.telegram.ui.TwoStepVerificationActivity.java

@Override
public View createView(Context context) {
    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setAllowOverlayTitle(false);
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
        @Override/*from   w  w  w  .  j  ava  2  s  .c om*/
        public void onItemClick(int id) {
            if (id == -1) {
                finishFragment();
            } else if (id == done_button) {
                processDone();
            }
        }
    });

    fragmentView = new FrameLayout(context);
    FrameLayout frameLayout = (FrameLayout) fragmentView;
    frameLayout.setBackgroundColor(ContextCompat.getColor(context, R.color.settings_background));

    ActionBarMenu menu = actionBar.createMenu();
    doneItem = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56));

    scrollView = new ScrollView(context);
    scrollView.setFillViewport(true);
    frameLayout.addView(scrollView);
    FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) scrollView.getLayoutParams();
    layoutParams.width = LayoutHelper.MATCH_PARENT;
    layoutParams.height = LayoutHelper.MATCH_PARENT;
    scrollView.setLayoutParams(layoutParams);

    LinearLayout linearLayout = new LinearLayout(context);
    linearLayout.setOrientation(LinearLayout.VERTICAL);
    scrollView.addView(linearLayout);
    ScrollView.LayoutParams layoutParams2 = (ScrollView.LayoutParams) linearLayout.getLayoutParams();
    layoutParams2.width = ScrollView.LayoutParams.MATCH_PARENT;
    layoutParams2.height = ScrollView.LayoutParams.WRAP_CONTENT;
    linearLayout.setLayoutParams(layoutParams2);

    titleTextView = new TextView(context);
    //titleTextView.setTextColor(0xff757575);
    titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
    titleTextView.setGravity(Gravity.CENTER_HORIZONTAL);
    linearLayout.addView(titleTextView);
    LinearLayout.LayoutParams layoutParams3 = (LinearLayout.LayoutParams) titleTextView.getLayoutParams();
    layoutParams3.width = LayoutHelper.WRAP_CONTENT;
    layoutParams3.height = LayoutHelper.WRAP_CONTENT;
    layoutParams3.gravity = Gravity.CENTER_HORIZONTAL;
    layoutParams3.topMargin = AndroidUtilities.dp(38);
    titleTextView.setLayoutParams(layoutParams3);

    passwordEditText = new EditText(context);
    passwordEditText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
    //passwordEditText.setTextColor(0xff000000);
    passwordEditText.setMaxLines(1);
    passwordEditText.setLines(1);
    passwordEditText.setGravity(Gravity.CENTER_HORIZONTAL);
    passwordEditText.setSingleLine(true);
    passwordEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
    passwordEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
    passwordEditText.setTypeface(Typeface.DEFAULT);
    AndroidUtilities.clearCursorDrawable(passwordEditText);
    linearLayout.addView(passwordEditText);
    layoutParams3 = (LinearLayout.LayoutParams) passwordEditText.getLayoutParams();
    layoutParams3.topMargin = AndroidUtilities.dp(32);
    layoutParams3.height = AndroidUtilities.dp(36);
    layoutParams3.leftMargin = AndroidUtilities.dp(40);
    layoutParams3.rightMargin = AndroidUtilities.dp(40);
    layoutParams3.gravity = Gravity.TOP | Gravity.LEFT;
    layoutParams3.width = LayoutHelper.MATCH_PARENT;
    passwordEditText.setLayoutParams(layoutParams3);
    passwordEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
            if (i == EditorInfo.IME_ACTION_NEXT || i == EditorInfo.IME_ACTION_DONE) {
                processDone();
                return true;
            }
            return false;
        }
    });
    passwordEditText.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        public void onDestroyActionMode(ActionMode mode) {
        }

        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            return false;
        }
    });

    bottomTextView = new TextView(context);
    //bottomTextView.setTextColor(0xff757575);
    bottomTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    bottomTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP);
    bottomTextView.setText(LocaleController.getString("YourEmailInfo", R.string.YourEmailInfo));
    linearLayout.addView(bottomTextView);
    layoutParams3 = (LinearLayout.LayoutParams) bottomTextView.getLayoutParams();
    layoutParams3.width = LayoutHelper.WRAP_CONTENT;
    layoutParams3.height = LayoutHelper.WRAP_CONTENT;
    layoutParams3.gravity = (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP;
    layoutParams3.topMargin = AndroidUtilities.dp(30);
    layoutParams3.leftMargin = AndroidUtilities.dp(40);
    layoutParams3.rightMargin = AndroidUtilities.dp(40);
    bottomTextView.setLayoutParams(layoutParams3);

    LinearLayout linearLayout2 = new LinearLayout(context);
    linearLayout2.setGravity(Gravity.BOTTOM | Gravity.CENTER_VERTICAL);
    linearLayout.addView(linearLayout2);
    layoutParams3 = (LinearLayout.LayoutParams) linearLayout2.getLayoutParams();
    layoutParams3.width = LayoutHelper.MATCH_PARENT;
    layoutParams3.height = LayoutHelper.MATCH_PARENT;
    linearLayout2.setLayoutParams(layoutParams3);

    bottomButton = new TextView(context);
    bottomButton.setTextColor(0xff4d83b3);
    bottomButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    bottomButton.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.BOTTOM);
    bottomButton.setText(LocaleController.getString("YourEmailSkip", R.string.YourEmailSkip));
    bottomButton.setPadding(0, AndroidUtilities.dp(10), 0, 0);
    linearLayout2.addView(bottomButton);
    layoutParams3 = (LinearLayout.LayoutParams) bottomButton.getLayoutParams();
    layoutParams3.width = LayoutHelper.WRAP_CONTENT;
    layoutParams3.height = LayoutHelper.WRAP_CONTENT;
    layoutParams3.gravity = (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.BOTTOM;
    layoutParams3.bottomMargin = AndroidUtilities.dp(14);
    layoutParams3.leftMargin = AndroidUtilities.dp(40);
    layoutParams3.rightMargin = AndroidUtilities.dp(40);
    bottomButton.setLayoutParams(layoutParams3);
    bottomButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (type == 0) {
                if (currentPassword.has_recovery) {
                    needShowProgress();
                    TLRPC.TL_auth_requestPasswordRecovery req = new TLRPC.TL_auth_requestPasswordRecovery();
                    ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
                        @Override
                        public void run(final TLObject response, final TLRPC.TL_error error) {
                            AndroidUtilities.runOnUIThread(new Runnable() {
                                @Override
                                public void run() {
                                    needHideProgress();
                                    if (error == null) {
                                        final TLRPC.TL_auth_passwordRecovery res = (TLRPC.TL_auth_passwordRecovery) response;
                                        AlertDialog.Builder builder = new AlertDialog.Builder(
                                                getParentActivity());
                                        builder.setMessage(LocaleController.formatString("RestoreEmailSent",
                                                R.string.RestoreEmailSent, res.email_pattern));
                                        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) {
                                                        TwoStepVerificationActivity fragment = new TwoStepVerificationActivity(
                                                                1);
                                                        fragment.currentPassword = currentPassword;
                                                        fragment.currentPassword.email_unconfirmed_pattern = res.email_pattern;
                                                        fragment.passwordSetState = 4;
                                                        presentFragment(fragment);
                                                    }
                                                });
                                        Dialog dialog = showDialog(builder.create());
                                        if (dialog != null) {
                                            dialog.setCanceledOnTouchOutside(false);
                                            dialog.setCancelable(false);
                                        }
                                    } else {
                                        if (error.text.startsWith("FLOOD_WAIT")) {
                                            int time = Utilities.parseInt(error.text);
                                            String timeString;
                                            if (time < 60) {
                                                timeString = LocaleController.formatPluralString("Seconds",
                                                        time);
                                            } else {
                                                timeString = LocaleController.formatPluralString("Minutes",
                                                        time / 60);
                                            }
                                            showAlertWithText(
                                                    LocaleController.getString("AppName", R.string.AppName),
                                                    LocaleController.formatString("FloodWaitTime",
                                                            R.string.FloodWaitTime, timeString));
                                        } else {
                                            showAlertWithText(
                                                    LocaleController.getString("AppName", R.string.AppName),
                                                    error.text);
                                        }
                                    }
                                }
                            });
                        }
                    }, ConnectionsManager.RequestFlagFailOnServerErrors
                            | ConnectionsManager.RequestFlagWithoutLogin);
                } else {
                    showAlertWithText(
                            LocaleController.getString("RestorePasswordNoEmailTitle",
                                    R.string.RestorePasswordNoEmailTitle),
                            LocaleController.getString("RestorePasswordNoEmailText",
                                    R.string.RestorePasswordNoEmailText));
                }
            } else {
                if (passwordSetState == 4) {
                    showAlertWithText(
                            LocaleController.getString("RestorePasswordNoEmailTitle",
                                    R.string.RestorePasswordNoEmailTitle),
                            LocaleController.getString("RestoreEmailTroubleText",
                                    R.string.RestoreEmailTroubleText));
                } else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                    builder.setMessage(LocaleController.getString("YourEmailSkipWarningText",
                            R.string.YourEmailSkipWarningText));
                    builder.setTitle(
                            LocaleController.getString("YourEmailSkipWarning", R.string.YourEmailSkipWarning));
                    builder.setPositiveButton(
                            LocaleController.getString("YourEmailSkip", R.string.YourEmailSkip),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    email = "";
                                    setNewPassword(false);
                                }
                            });
                    builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                    showDialog(builder.create());
                }
            }
        }
    });

    if (type == 0) {
        progressView = new FrameLayout(context);
        frameLayout.addView(progressView);
        layoutParams = (FrameLayout.LayoutParams) progressView.getLayoutParams();
        layoutParams.width = LayoutHelper.MATCH_PARENT;
        layoutParams.height = LayoutHelper.MATCH_PARENT;
        progressView.setLayoutParams(layoutParams);
        progressView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });

        ProgressBar progressBar = new ProgressBar(context);
        progressView.addView(progressBar);
        layoutParams = (FrameLayout.LayoutParams) progressView.getLayoutParams();
        layoutParams.width = LayoutHelper.WRAP_CONTENT;
        layoutParams.height = LayoutHelper.WRAP_CONTENT;
        layoutParams.gravity = Gravity.CENTER;
        progressView.setLayoutParams(layoutParams);

        listView = new ListView(context);
        listView.setDivider(null);
        listView.setEmptyView(progressView);
        listView.setDividerHeight(0);
        listView.setVerticalScrollBarEnabled(false);
        listView.setDrawSelectorOnTop(true);
        frameLayout.addView(listView);
        layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams();
        layoutParams.width = LayoutHelper.MATCH_PARENT;
        layoutParams.height = LayoutHelper.MATCH_PARENT;
        layoutParams.gravity = Gravity.TOP;
        listView.setLayoutParams(layoutParams);
        listView.setAdapter(listAdapter = new ListAdapter(context));
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
                if (i == setPasswordRow || i == changePasswordRow) {
                    TwoStepVerificationActivity fragment = new TwoStepVerificationActivity(1);
                    fragment.currentPasswordHash = currentPasswordHash;
                    fragment.currentPassword = currentPassword;
                    presentFragment(fragment);
                } else if (i == setRecoveryEmailRow || i == changeRecoveryEmailRow) {
                    TwoStepVerificationActivity fragment = new TwoStepVerificationActivity(1);
                    fragment.currentPasswordHash = currentPasswordHash;
                    fragment.currentPassword = currentPassword;
                    fragment.emailOnly = true;
                    fragment.passwordSetState = 3;
                    presentFragment(fragment);
                } else if (i == turnPasswordOffRow || i == abortPasswordRow) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                    builder.setMessage(LocaleController.getString("TurnPasswordOffQuestion",
                            R.string.TurnPasswordOffQuestion));
                    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) {
                                    setNewPassword(true);
                                }
                            });
                    builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                    showDialog(builder.create());
                }
            }
        });

        updateRows();

        actionBar.setTitle(LocaleController.getString("TwoStepVerification", R.string.TwoStepVerification));
        titleTextView.setText(
                LocaleController.getString("PleaseEnterCurrentPassword", R.string.PleaseEnterCurrentPassword));
    } else if (type == 1) {
        setPasswordSetState(passwordSetState);
    }

    return fragmentView;
}

From source file:de.mkrtchyan.recoverytools.RecoveryTools.java

public void showFlashHistory(View view) {
    final boolean RecoveryHistory = view.getTag().toString().equals("recovery");
    String PREF_KEY;/*from  w  w w . j a  v a 2s .  co m*/
    if (RecoveryHistory) {
        PREF_KEY = PREF_KEY_RECOVERY_HISTORY;
    } else {
        PREF_KEY = PREF_KEY_KERNEL_HISTORY;
    }
    final ArrayList<File> HistoryFiles = new ArrayList<File>();
    final ArrayList<String> HistoryFileNames = new ArrayList<String>();
    final Dialog HistoryDialog = new Dialog(mContext);
    HistoryDialog.setTitle(R.string.sHistory);
    ListView HistoryList = new ListView(mContext);
    File tmp;
    for (int i = 0; i < 5; i++) {
        tmp = new File(Common.getStringPref(mContext, PREF_NAME, PREF_KEY + String.valueOf(i)));
        if (!tmp.exists())
            Common.setStringPref(mContext, PREF_NAME, PREF_KEY + String.valueOf(i), "");
        else {
            HistoryFiles.add(tmp);
            HistoryFileNames.add(tmp.getName());
        }
    }
    HistoryList.setAdapter(
            new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_1, HistoryFileNames));
    HistoryList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            if (HistoryFiles.get(arg2).exists()) {
                if (RecoveryHistory) {
                    fRECOVERY = HistoryFiles.get(arg2);
                    rRecoveryFlasher.run();
                } else {
                    fKERNEL = HistoryFiles.get(arg2);
                    rKernelFlasher.run();
                }
                HistoryDialog.dismiss();
            } else {
                Toast.makeText(mContext, R.string.no_choosed, Toast.LENGTH_SHORT).show();
            }
        }
    });
    HistoryDialog.setContentView(HistoryList);
    if (HistoryFileNames.toArray().length > 0) {
        HistoryDialog.show();
    } else {
        Toast.makeText(mContext, R.string.no_history, Toast.LENGTH_SHORT).show();
    }

}

From source file:com.df.app.carCheck.VehicleInfoLayout.java

/**
 * edit/*from   ww  w  . j av  a  2 s .c  o  m*/
 */
private void showListDialog(int titleId, ArrayAdapter<String> adapter, final Handler handler) {
    View view1 = ((Activity) getContext()).getLayoutInflater().inflate(R.layout.popup_layout, null);

    final AlertDialog dialog = new AlertDialog.Builder(getContext()).setView(view1).create();

    TableLayout contentArea = (TableLayout) view1.findViewById(R.id.contentArea);
    final ListView listView = new ListView(view1.getContext());
    listView.setAdapter(adapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            handler.sendEmptyMessage(i);
            dialog.dismiss();
        }
    });
    contentArea.addView(listView);

    setTextView(view1, R.id.title, getResources().getString(titleId));

    dialog.show();
}

From source file:net.inbox.InboxMessage.java

/**
 * Dialog picking the folder for the attachment download.
 **///from   w  ww  .  j a v a2s. c  om
private void dialog_folder_picker() {
    chosen_folder = null;
    refresh_folders(1);

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(getString(R.string.folder_title));
    builder.setPositiveButton(getString(R.string.btn_up_one_level), null);

    // Populating folders
    ListView lv_folders = new ListView(this);
    lv_folders.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            // Obtain the index of the chosen folder
            String str = (String) parent.getItemAtPosition(position);
            for (File f : f_folders) {
                if (f.getName().equals(str)) {
                    current_path = f;
                    break;
                }
            }
            refresh_folders(2);
            lv_adapter.notifyDataSetChanged();
        }
    });

    // Continuing download
    lv_folders.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
            // Obtain the index of the chosen folder
            String str = (String) parent.getItemAtPosition(position);
            for (File f : f_folders) {
                if (f.getName().equals(str)) {
                    chosen_folder = f;
                    break;
                }
            }
            dialog_folder_picker.dismiss();
            if (chosen_att == null) {
                full_message_tests();
            } else {
                attachment_tests();
            }
            return true;
        }
    });

    lv_adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, s_folders);
    lv_folders.setAdapter(lv_adapter);

    builder.setView(lv_folders);
    dialog_folder_picker = builder.show();

    // Reassigning button to prevent early dialog ending
    dialog_folder_picker.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (current_path.getParent() != null) {
                refresh_folders(3);
                lv_adapter.notifyDataSetChanged();
            }
        }
    });
}

From source file:org.pouyadr.ui.LocationActivity.java

@Override
public View createView(Context context) {
    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setAllowOverlayTitle(true);
    if (AndroidUtilities.isTablet()) {
        actionBar.setOccupyStatusBar(false);
    }/*w w  w. ja va 2s.  c  o  m*/
    actionBar.setAddToContainer(messageObject != null);

    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
        @Override
        public void onItemClick(int id) {
            if (id == -1) {
                finishFragment();
            } else if (id == map_list_menu_map) {
                if (googleMap != null) {
                    googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                }
            } else if (id == map_list_menu_satellite) {
                if (googleMap != null) {
                    googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
                }
            } else if (id == map_list_menu_hybrid) {
                if (googleMap != null) {
                    googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
                }
            } else if (id == share) {
                try {
                    double lat = messageObject.messageOwner.media.geo.lat;
                    double lon = messageObject.messageOwner.media.geo._long;
                    getParentActivity().startActivity(new Intent(android.content.Intent.ACTION_VIEW,
                            Uri.parse("geo:" + lat + "," + lon + "?q=" + lat + "," + lon)));
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
            }
        }
    });

    ActionBarMenu menu = actionBar.createMenu();
    if (messageObject != null) {
        if (messageObject.messageOwner.media.title != null
                && messageObject.messageOwner.media.title.length() > 0) {
            actionBar.setTitle(messageObject.messageOwner.media.title);
            if (messageObject.messageOwner.media.address != null
                    && messageObject.messageOwner.media.address.length() > 0) {
                actionBar.setSubtitle(messageObject.messageOwner.media.address);
            }
        } else {
            actionBar.setTitle(LocaleController.getString("ChatLocation", R.string.ChatLocation));
        }
        menu.addItem(share, R.drawable.share);
    } else {
        actionBar.setTitle(LocaleController.getString("ShareLocation", R.string.ShareLocation));

        ActionBarMenuItem item = menu.addItem(0, R.drawable.ic_ab_search).setIsSearchField(true)
                .setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() {
                    @Override
                    public void onSearchExpand() {
                        searching = true;
                        listView.setVisibility(View.GONE);
                        mapViewClip.setVisibility(View.GONE);
                        searchListView.setVisibility(View.VISIBLE);
                        searchListView.setEmptyView(emptyTextLayout);
                    }

                    @Override
                    public void onSearchCollapse() {
                        searching = false;
                        searchWas = false;
                        searchListView.setEmptyView(null);
                        listView.setVisibility(View.VISIBLE);
                        mapViewClip.setVisibility(View.VISIBLE);
                        searchListView.setVisibility(View.GONE);
                        emptyTextLayout.setVisibility(View.GONE);
                        searchAdapter.searchDelayed(null, null);
                    }

                    @Override
                    public void onTextChanged(EditText editText) {
                        if (searchAdapter == null) {
                            return;
                        }
                        String text = editText.getText().toString();
                        if (text.length() != 0) {
                            searchWas = true;
                        }
                        searchAdapter.searchDelayed(text, userLocation);
                    }
                });
        item.getSearchField().setHint(LocaleController.getString("Search", R.string.Search));
    }

    ActionBarMenuItem item = menu.addItem(0, R.drawable.ic_ab_other);
    item.addSubItem(map_list_menu_map, LocaleController.getString("Map", R.string.Map), 0);
    item.addSubItem(map_list_menu_satellite, LocaleController.getString("Satellite", R.string.Satellite), 0);
    item.addSubItem(map_list_menu_hybrid, LocaleController.getString("Hybrid", R.string.Hybrid), 0);
    fragmentView = new FrameLayout(context) {
        private boolean first = true;

        @Override
        protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
            super.onLayout(changed, left, top, right, bottom);

            if (changed) {
                fixLayoutInternal(first);
                first = false;
            }
        }
    };
    FrameLayout frameLayout = (FrameLayout) fragmentView;

    locationButton = new ImageView(context);
    locationButton.setBackgroundResource(R.drawable.floating_user_states);
    locationButton.setImageResource(R.drawable.myloc_on);
    locationButton.setScaleType(ImageView.ScaleType.CENTER);
    if (Build.VERSION.SDK_INT >= 21) {
        StateListAnimator animator = new StateListAnimator();
        animator.addState(new int[] { android.R.attr.state_pressed },
                ObjectAnimator
                        .ofFloat(locationButton, "translationZ", AndroidUtilities.dp(2), AndroidUtilities.dp(4))
                        .setDuration(200));
        animator.addState(new int[] {},
                ObjectAnimator
                        .ofFloat(locationButton, "translationZ", AndroidUtilities.dp(4), AndroidUtilities.dp(2))
                        .setDuration(200));
        locationButton.setStateListAnimator(animator);
        locationButton.setOutlineProvider(new ViewOutlineProvider() {
            @Override
            public void getOutline(View view, Outline outline) {
                outline.setOval(0, 0, AndroidUtilities.dp(56), AndroidUtilities.dp(56));
            }
        });
    }

    if (messageObject != null) {
        mapView = new MapView(context);
        frameLayout.setBackgroundDrawable(new MapPlaceholderDrawable());
        mapView.onCreate(null);
        try {
            MapsInitializer.initialize(context);
            //                googleMap = mapView.getMap();
        } catch (Exception e) {
            FileLog.e("tmessages", e);
        }

        FrameLayout bottomView = new FrameLayout(context);
        bottomView.setBackgroundResource(R.drawable.location_panel);
        frameLayout.addView(bottomView,
                LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 60, Gravity.LEFT | Gravity.BOTTOM));
        bottomView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (userLocation != null) {
                    LatLng latLng = new LatLng(userLocation.getLatitude(), userLocation.getLongitude());
                    if (googleMap != null) {
                        CameraUpdate position = CameraUpdateFactory.newLatLngZoom(latLng,
                                googleMap.getMaxZoomLevel() - 4);
                        googleMap.animateCamera(position);
                    }
                }
            }
        });

        avatarImageView = new BackupImageView(context);
        avatarImageView.setRoundRadius(AndroidUtilities.dp(20));
        bottomView.addView(avatarImageView,
                LayoutHelper.createFrame(40, 40,
                        Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT),
                        LocaleController.isRTL ? 0 : 12, 12, LocaleController.isRTL ? 12 : 0, 0));

        nameTextView = new TextView(context);
        nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
        nameTextView.setTextColor(0xff212121);
        nameTextView.setMaxLines(1);
        nameTextView.setTypeface(AndroidUtilities.getTypeface(org.pouyadr.finalsoft.Fonts.CurrentFont()));
        nameTextView.setEllipsize(TextUtils.TruncateAt.END);
        nameTextView.setSingleLine(true);
        nameTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT);
        bottomView.addView(nameTextView,
                LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT,
                        Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT),
                        LocaleController.isRTL ? 12 : 72, 10, LocaleController.isRTL ? 72 : 12, 0));

        distanceTextView = new TextView(context);
        distanceTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
        distanceTextView.setTextColor(0xff2f8cc9);
        distanceTextView.setMaxLines(1);
        distanceTextView.setEllipsize(TextUtils.TruncateAt.END);
        distanceTextView.setSingleLine(true);
        distanceTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT);
        bottomView.addView(distanceTextView,
                LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT,
                        Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT),
                        LocaleController.isRTL ? 12 : 72, 33, LocaleController.isRTL ? 72 : 12, 0));

        userLocation = new Location("network");
        userLocation.setLatitude(messageObject.messageOwner.media.geo.lat);
        userLocation.setLongitude(messageObject.messageOwner.media.geo._long);
        if (googleMap != null) {
            LatLng latLng = new LatLng(userLocation.getLatitude(), userLocation.getLongitude());
            try {
                googleMap.addMarker(new MarkerOptions().position(latLng)
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.map_pin)));
            } catch (Exception e) {
                FileLog.e("tmessages", e);
            }
            CameraUpdate position = CameraUpdateFactory.newLatLngZoom(latLng, googleMap.getMaxZoomLevel() - 4);
            googleMap.moveCamera(position);
        }

        ImageView routeButton = new ImageView(context);
        routeButton.setBackgroundResource(R.drawable.floating_states);
        routeButton.setImageResource(R.drawable.navigate);
        routeButton.setScaleType(ImageView.ScaleType.CENTER);
        if (Build.VERSION.SDK_INT >= 21) {
            StateListAnimator animator = new StateListAnimator();
            animator.addState(new int[] { android.R.attr.state_pressed }, ObjectAnimator
                    .ofFloat(routeButton, "translationZ", AndroidUtilities.dp(2), AndroidUtilities.dp(4))
                    .setDuration(200));
            animator.addState(new int[] {}, ObjectAnimator
                    .ofFloat(routeButton, "translationZ", AndroidUtilities.dp(4), AndroidUtilities.dp(2))
                    .setDuration(200));
            routeButton.setStateListAnimator(animator);
            routeButton.setOutlineProvider(new ViewOutlineProvider() {
                @Override
                public void getOutline(View view, Outline outline) {
                    outline.setOval(0, 0, AndroidUtilities.dp(56), AndroidUtilities.dp(56));
                }
            });
        }
        frameLayout.addView(routeButton,
                LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT,
                        (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.BOTTOM,
                        LocaleController.isRTL ? 14 : 0, 0, LocaleController.isRTL ? 0 : 14, 28));
        routeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT >= 23) {
                    Activity activity = getParentActivity();
                    if (activity != null) {
                        if (activity.checkSelfPermission(
                                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                            showPermissionAlert(true);
                            return;
                        }
                    }
                }
                if (myLocation != null) {
                    try {
                        Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
                                Uri.parse(String.format(Locale.US,
                                        "http://maps.google.com/maps?saddr=%f,%f&daddr=%f,%f",
                                        myLocation.getLatitude(), myLocation.getLongitude(),
                                        messageObject.messageOwner.media.geo.lat,
                                        messageObject.messageOwner.media.geo._long)));
                        getParentActivity().startActivity(intent);
                    } catch (Exception e) {
                        FileLog.e("tmessages", e);
                    }
                }
            }
        });

        frameLayout.addView(locationButton,
                LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT,
                        (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.BOTTOM,
                        LocaleController.isRTL ? 14 : 0, 0, LocaleController.isRTL ? 0 : 14, 100));
        locationButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT >= 23) {
                    Activity activity = getParentActivity();
                    if (activity != null) {
                        if (activity.checkSelfPermission(
                                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                            showPermissionAlert(true);
                            return;
                        }
                    }
                }
                if (myLocation != null && googleMap != null) {
                    googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                            new LatLng(myLocation.getLatitude(), myLocation.getLongitude()),
                            googleMap.getMaxZoomLevel() - 4));
                }
            }
        });
    } else {
        searchWas = false;
        searching = false;
        mapViewClip = new FrameLayout(context);
        mapViewClip.setBackgroundDrawable(new MapPlaceholderDrawable());
        if (adapter != null) {
            adapter.destroy();
        }
        if (searchAdapter != null) {
            searchAdapter.destroy();
        }

        listView = new ListView(context);
        listView.setAdapter(adapter = new LocationActivityAdapter(context));
        listView.setVerticalScrollBarEnabled(false);
        listView.setDividerHeight(0);
        listView.setDivider(null);
        frameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
                LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP));
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                    int totalItemCount) {
                if (totalItemCount == 0) {
                    return;
                }
                updateClipView(firstVisibleItem);
            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 1) {
                    if (delegate != null && userLocation != null) {
                        TLRPC.TL_messageMediaGeo location = new TLRPC.TL_messageMediaGeo();
                        location.geo = new TLRPC.TL_geoPoint();
                        location.geo.lat = userLocation.getLatitude();
                        location.geo._long = userLocation.getLongitude();
                        delegate.didSelectLocation(location);
                    }
                    finishFragment();
                } else {
                    TLRPC.TL_messageMediaVenue object = adapter.getItem(position);
                    if (object != null && delegate != null) {
                        delegate.didSelectLocation(object);
                    }
                    finishFragment();
                }
            }
        });
        adapter.setDelegate(new BaseLocationAdapter.BaseLocationAdapterDelegate() {
            @Override
            public void didLoadedSearchResult(ArrayList<TLRPC.TL_messageMediaVenue> places) {
                if (!wasResults && !places.isEmpty()) {
                    wasResults = true;
                }
            }
        });
        adapter.setOverScrollHeight(overScrollHeight);

        frameLayout.addView(mapViewClip, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
                LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP));

        mapView = new MapView(context) {
            @Override
            public boolean onInterceptTouchEvent(MotionEvent ev) {
                if (Build.VERSION.SDK_INT >= 11) {
                    if (ev.getAction() == MotionEvent.ACTION_DOWN) {
                        if (animatorSet != null) {
                            animatorSet.cancel();
                        }
                        animatorSet = new AnimatorSet();
                        animatorSet.setDuration(200);
                        animatorSet.playTogether(
                                ObjectAnimator.ofFloat(markerImageView, "translationY",
                                        markerTop + -AndroidUtilities.dp(10)),
                                ObjectAnimator.ofFloat(markerXImageView, "alpha", 1.0f));
                        animatorSet.start();
                    } else if (ev.getAction() == MotionEvent.ACTION_UP) {
                        if (animatorSet != null) {
                            animatorSet.cancel();
                        }
                        animatorSet = new AnimatorSet();
                        animatorSet.setDuration(200);
                        animatorSet.playTogether(
                                ObjectAnimator.ofFloat(markerImageView, "translationY", markerTop),
                                ObjectAnimator.ofFloat(markerXImageView, "alpha", 0.0f));
                        animatorSet.start();
                    }
                }
                if (ev.getAction() == MotionEvent.ACTION_MOVE) {
                    if (!userLocationMoved) {
                        if (Build.VERSION.SDK_INT >= 11) {
                            AnimatorSet animatorSet = new AnimatorSet();
                            animatorSet.setDuration(200);
                            animatorSet.play(ObjectAnimator.ofFloat(locationButton, "alpha", 1.0f));
                            animatorSet.start();
                        } else {
                            locationButton.setVisibility(VISIBLE);
                        }
                        userLocationMoved = true;
                    }
                    if (googleMap != null && userLocation != null) {
                        userLocation.setLatitude(googleMap.getCameraPosition().target.latitude);
                        userLocation.setLongitude(googleMap.getCameraPosition().target.longitude);
                    }
                    adapter.setCustomLocation(userLocation);
                }
                return super.onInterceptTouchEvent(ev);
            }
        };
        try {
            mapView.onCreate(null);
        } catch (Exception e) {
            FileLog.e("tmessages", e);
        }
        try {
            MapsInitializer.initialize(context);
            //                googleMap = mapView.getMap();
        } catch (Exception e) {
            FileLog.e("tmessages", e);
        }

        View shadow = new View(context);
        shadow.setBackgroundResource(R.drawable.header_shadow_reverse);
        mapViewClip.addView(shadow,
                LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 3, Gravity.LEFT | Gravity.BOTTOM));

        markerImageView = new ImageView(context);
        markerImageView.setImageResource(R.drawable.map_pin);
        mapViewClip.addView(markerImageView,
                LayoutHelper.createFrame(24, 42, Gravity.TOP | Gravity.CENTER_HORIZONTAL));

        if (Build.VERSION.SDK_INT >= 11) {
            markerXImageView = new ImageView(context);
            markerXImageView.setAlpha(0.0f);
            markerXImageView.setImageResource(R.drawable.place_x);
            mapViewClip.addView(markerXImageView,
                    LayoutHelper.createFrame(14, 14, Gravity.TOP | Gravity.CENTER_HORIZONTAL));
        }

        mapViewClip.addView(locationButton,
                LayoutHelper.createFrame(Build.VERSION.SDK_INT >= 21 ? 56 : 60,
                        Build.VERSION.SDK_INT >= 21 ? 56 : 60,
                        (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.BOTTOM,
                        LocaleController.isRTL ? 14 : 0, 0, LocaleController.isRTL ? 0 : 14, 14));
        locationButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT >= 23) {
                    Activity activity = getParentActivity();
                    if (activity != null) {
                        if (activity.checkSelfPermission(
                                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                            showPermissionAlert(false);
                            return;
                        }
                    }
                }
                if (myLocation != null && googleMap != null) {
                    if (Build.VERSION.SDK_INT >= 11) {
                        AnimatorSet animatorSet = new AnimatorSet();
                        animatorSet.setDuration(200);
                        animatorSet.play(ObjectAnimator.ofFloat(locationButton, "alpha", 0.0f));
                        animatorSet.start();
                    } else {
                        locationButton.setVisibility(View.INVISIBLE);
                    }
                    adapter.setCustomLocation(null);
                    userLocationMoved = false;
                    googleMap.animateCamera(CameraUpdateFactory
                            .newLatLng(new LatLng(myLocation.getLatitude(), myLocation.getLongitude())));
                }
            }
        });
        if (Build.VERSION.SDK_INT >= 11) {
            locationButton.setAlpha(0.0f);
        } else {
            locationButton.setVisibility(View.INVISIBLE);
        }

        emptyTextLayout = new LinearLayout(context);
        emptyTextLayout.setVisibility(View.GONE);
        emptyTextLayout.setOrientation(LinearLayout.VERTICAL);
        frameLayout.addView(emptyTextLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
                LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP, 0, 100, 0, 0));
        emptyTextLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });

        TextView emptyTextView = new TextView(context);
        emptyTextView.setTextColor(0xff808080);
        emptyTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
        emptyTextView.setGravity(Gravity.CENTER);
        emptyTextView.setText(LocaleController.getString("NoResult", R.string.NoResult));
        emptyTextLayout.addView(emptyTextView,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, 0.5f));

        FrameLayout frameLayoutEmpty = new FrameLayout(context);
        emptyTextLayout.addView(frameLayoutEmpty,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, 0.5f));

        searchListView = new ListView(context);
        searchListView.setVisibility(View.GONE);
        searchListView.setDividerHeight(0);
        searchListView.setDivider(null);
        searchListView.setAdapter(searchAdapter = new LocationActivitySearchAdapter(context));
        frameLayout.addView(searchListView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
                LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP));
        searchListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == SCROLL_STATE_TOUCH_SCROLL && searching && searchWas) {
                    AndroidUtilities.hideKeyboard(getParentActivity().getCurrentFocus());
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                    int totalItemCount) {

            }
        });
        searchListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TLRPC.TL_messageMediaVenue object = searchAdapter.getItem(position);
                if (object != null && delegate != null) {
                    delegate.didSelectLocation(object);
                }
                finishFragment();
            }
        });

        if (googleMap != null) {
            userLocation = new Location("network");
            userLocation.setLatitude(20.659322);
            userLocation.setLongitude(-11.406250);
        }

        frameLayout.addView(actionBar);
    }

    if (googleMap != null) {
        try {
            googleMap.setMyLocationEnabled(true);
        } catch (Exception e) {
            FileLog.e("tmessages", e);
        }
        googleMap.getUiSettings().setMyLocationButtonEnabled(false);
        googleMap.getUiSettings().setZoomControlsEnabled(false);
        googleMap.getUiSettings().setCompassEnabled(false);
        googleMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
            @Override
            public void onMyLocationChange(Location location) {
                positionMarker(location);
            }
        });
        positionMarker(myLocation = getLastLocation());
    }

    return fragmentView;
}

From source file:terse.a1.TerseActivity.java

private void viewPath9display(String path, LayoutParams widgetParams) {
    String explain;/*from w  ww . j  av  a  2s. 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:nl.sogeti.android.gpstracker.viewer.TrackList.java

private void ensureList() {
    if (mList != null) {
        return;//from w w  w  .j  a  v  a2s .  c om
    }
    setContentView(new ListView(this));

}