Example usage for android.widget TextView TextView

List of usage examples for android.widget TextView TextView

Introduction

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

Prototype

public TextView(Context context) 

Source Link

Usage

From source file:com.hichinaschool.flashcards.anki.multimediacard.activity.MultimediaCardEditorActivity.java

private void createNewViewer(LinearLayout linearLayout, final IField field, final int index) {

    final MultimediaCardEditorActivity context = this;

    switch (field.getType()) {
    case TEXT:/*from w  w  w  .j  a  v a2  s .com*/

        // Create a text field and an edit button, opening editing for
        // the
        // text field

        TextView textView = new TextView(this);
        textView.setText(field.getText());
        linearLayout.addView(textView, LinearLayout.LayoutParams.MATCH_PARENT);

        break;

    case IMAGE:

        ImageView imgView = new ImageView(this);
        //
        // BitmapFactory.Options options = new BitmapFactory.Options();
        // options.inSampleSize = 2;
        // Bitmap bm = BitmapFactory.decodeFile(myJpgPath, options);
        // jpgView.setImageBitmap(bm);

        LinearLayout.LayoutParams p = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

        File f = new File(field.getImagePath());

        Bitmap b = BitmapUtil.decodeFile(f, getMaxImageSize());

        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion >= android.os.Build.VERSION_CODES.ECLAIR) {
            b = ExifUtil.rotateFromCamera(f, b);
        }

        imgView.setImageBitmap(b);

        imgView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        imgView.setAdjustViewBounds(true);

        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);

        int height = metrics.heightPixels;
        int width = metrics.widthPixels;

        imgView.setMaxHeight((int) Math.round(height * 0.6));
        imgView.setMaxWidth((int) Math.round(width * 0.7));
        linearLayout.addView(imgView, p);

        break;
    case AUDIO:
        AudioView audioView = AudioView.createPlayerInstance(this, R.drawable.av_play, R.drawable.av_pause,
                R.drawable.av_stop, field.getAudioPath());
        linearLayout.addView(audioView);
        break;

    default:
        Log.e("multimedia editor", "Unsupported field type found");
        break;
    }

    Button editButtonText = new Button(this);
    editButtonText.setText(gtxt(R.string.multimedia_editor_activity_edit_button));
    linearLayout.addView(editButtonText, LinearLayout.LayoutParams.MATCH_PARENT);

    editButtonText.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent i = new Intent(context, EditFieldActivity.class);
            putExtrasAndStartEditActivity(field, index, i);
        }

    });
}

From source file:net.networksaremadeofstring.rhybudd.ViewZenossEvent.java

/** Called when the activity is first created. */
@Override/*from   w w w  .  ja  v a  2 s. c om*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    BugSenseHandler.initAndStartSession(ViewZenossEvent.this, "44a76a8c");

    settings = PreferenceManager.getDefaultSharedPreferences(this);

    setContentView(R.layout.view_zenoss_event);

    try {
        actionbar = getActionBar();
        actionbar.setDisplayHomeAsUpEnabled(true);
        actionbar.setHomeButtonEnabled(true);
    } catch (Exception e) {
        BugSenseHandler.sendExceptionMessage("ViewZenossEvent", "OnCreate", e);
    }

    try {
        ((TextView) findViewById(R.id.EventTitle)).setText(getIntent().getStringExtra("Device"));
        ((TextView) findViewById(R.id.Summary)).setText(Html.fromHtml(getIntent().getStringExtra("Summary")));
        ((TextView) findViewById(R.id.LastTime)).setText(getIntent().getStringExtra("LastTime"));
        ((TextView) findViewById(R.id.EventCount))
                .setText("Count: " + Integer.toString(getIntent().getIntExtra("Count", 0)));
    } catch (Exception e) {
        //We don't need to much more than report it because the direct API request will sort it out for us.
        BugSenseHandler.sendExceptionMessage("ViewZenossEvent", "OnCreate", e);
    }

    firstLoadHandler = new Handler() {
        public void handleMessage(Message msg) {
            dialog.dismiss();
            try {
                if (EventObject.has("result")
                        && EventObject.getJSONObject("result").getBoolean("success") == true) {
                    //Log.i("Event",EventObject.toString(3));
                    TextView Title = (TextView) findViewById(R.id.EventTitle);
                    TextView Component = (TextView) findViewById(R.id.Componant);
                    TextView EventClass = (TextView) findViewById(R.id.EventClass);
                    TextView Summary = (TextView) findViewById(R.id.Summary);
                    TextView FirstTime = (TextView) findViewById(R.id.FirstTime);
                    TextView LastTime = (TextView) findViewById(R.id.LastTime);
                    LinearLayout logList;

                    EventDetails = EventObject.getJSONObject("result").getJSONArray("event").getJSONObject(0);

                    try {
                        if (EventDetails.getString("eventState").equals("Acknowledged")) {
                            ((ImageView) findViewById(R.id.ackIcon))
                                    .setImageResource(R.drawable.ic_acknowledged);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    //Log.e("EventDetails",EventDetails.toString(3));

                    try {
                        Title.setText(EventDetails.getString("device_title"));
                    } catch (Exception e) {
                        Title.setText("Unknown Device - Event Details");
                    }

                    try {
                        Component.setText(EventDetails.getString("component"));
                    } catch (Exception e) {
                        Component.setText("Unknown Component");
                    }

                    try {
                        EventClass.setText(EventDetails.getString("eventClassKey"));
                    } catch (Exception e) {
                        EventClass.setText("Unknown Event Class");
                    }

                    try {
                        ImageView img = (ImageView) findViewById(R.id.summaryImage);

                        URLImageParser p = new URLImageParser(img, ViewZenossEvent.this, Summary);
                        Spanned htmlSpan = Html.fromHtml(EventDetails.getString("message"), p, null);

                        Summary.setText(htmlSpan);
                        //Summary.setText(Html.fromHtml(EventDetails.getString("message")));

                        //((ImageView) findViewById(R.id.summaryImage)).setImageDrawable(p.drawable);
                        //Log.i("Summary",EventDetails.getString("message"));

                        //((TextView) findViewById(R.id.Summary)).setVisibility(View.GONE);
                        //((WebView) findViewById(R.id.summaryWebView)).loadData(EventDetails.getString("message"), "text/html", null);
                        //((WebView) findViewById(R.id.summaryWebView)).loadDataWithBaseURL(null, EventDetails.getString("message"), "text/html", "UTF-8", "about:blank");

                        try {
                            Summary.setMovementMethod(LinkMovementMethod.getInstance());
                        } catch (Exception e) {
                            //Worth a shot
                        }
                    } catch (Exception e) {
                        Summary.setText("No Summary available");
                    }

                    try {
                        FirstTime.setText(EventDetails.getString("firstTime"));
                    } catch (Exception e) {
                        FirstTime.setText("No Start Date Provided");
                    }

                    try {
                        LastTime.setText(EventDetails.getString("stateChange"));
                    } catch (Exception e) {
                        LastTime.setText("No Recent Date Provided");
                    }

                    try {
                        ((TextView) findViewById(R.id.EventCount))
                                .setText("Count: " + EventDetails.getString("count"));
                    } catch (Exception e) {
                        ((TextView) findViewById(R.id.EventCount)).setText("Count: ??");
                    }

                    try {
                        ((TextView) findViewById(R.id.Agent)).setText(EventDetails.getString("agent"));
                    } catch (Exception e) {
                        ((TextView) findViewById(R.id.Agent)).setText("unknown");
                    }

                    try {
                        JSONArray Log = EventDetails.getJSONArray("log");

                        int LogEntryCount = Log.length();

                        logList = (LinearLayout) findViewById(R.id.LogList);

                        if (LogEntryCount == 0) {
                            /*String[] LogEntries = {"No log entries could be found"};
                            ((ListView) findViewById(R.id.LogList)).setAdapter(new ArrayAdapter<String>(ViewZenossEvent.this, R.layout.search_simple,LogEntries));*/

                            TextView newLog = new TextView(ViewZenossEvent.this);
                            newLog.setText("No log entries could be found");

                            logList.addView(newLog);
                        } else {
                            LogEntries = new String[LogEntryCount];

                            for (int i = 0; i < LogEntryCount; i++) {
                                //LogEntries[i] = Log.getJSONArray(i).getString(0) + " set " + Log.getJSONArray(i).getString(2) +"\nAt: " + Log.getJSONArray(i).getString(1);

                                TextView newLog = new TextView(ViewZenossEvent.this);
                                newLog.setText(Html.fromHtml("<strong>" + Log.getJSONArray(i).getString(0)
                                        + "</strong> wrote " + Log.getJSONArray(i).getString(2)
                                        + "\n<br/><strong>At:</strong> " + Log.getJSONArray(i).getString(1)));
                                newLog.setPadding(0, 6, 0, 6);
                                logList.addView(newLog);
                            }

                            /*try
                            {
                               ((ListView) findViewById(R.id.LogList)).setAdapter(new ArrayAdapter<String>(ViewZenossEvent.this, R.layout.search_simple,LogEntries));
                            }
                            catch(Exception e)
                            {
                               Toast.makeText(getApplicationContext(), "There was an error trying process the log entries for this event.", Toast.LENGTH_SHORT).show();
                            }*/
                        }
                    } catch (Exception e) {
                        TextView newLog = new TextView(ViewZenossEvent.this);
                        newLog.setText("No log entries could be found");
                        newLog.setPadding(0, 6, 0, 6);
                        ((LinearLayout) findViewById(R.id.LogList)).addView(newLog);

                        /*String[] LogEntries = {"No log entries could be found"};
                        try
                        {
                           ((ListView) findViewById(R.id.LogList)).setAdapter(new ArrayAdapter<String>(ViewZenossEvent.this, R.layout.search_simple,LogEntries));
                        }
                        catch(Exception e1)
                        {
                           //BugSenseHandler.log("ViewZenossEvent-LogEntries", e1);
                        }*/
                    }
                } else {
                    //Log.e("ViewEvent",EventObject.toString(3));
                    Toast.makeText(ViewZenossEvent.this, "There was an error loading the Event details",
                            Toast.LENGTH_LONG).show();
                    //finish();
                }
            } catch (Exception e) {
                Toast.makeText(ViewZenossEvent.this,
                        "An error was encountered parsing the JSON. An error report has been sent.",
                        Toast.LENGTH_LONG).show();
                //BugSenseHandler.log("ViewZenossEvent", e);
            }
        }
    };

    dialog = new ProgressDialog(this);
    dialog.setTitle("Contacting Zenoss");
    dialog.setMessage("Please wait:\nLoading Event details....");
    dialog.show();
    dataPreload = new Thread() {
        public void run() {
            try {
                /*if(API == null)
                {
                   if(settings.getBoolean("httpBasicAuth", false))
                   {
                      API = new ZenossAPIv2(settings.getString("userName", ""), settings.getString("passWord", ""), settings.getString("URL", ""),settings.getString("BAUser", ""), settings.getString("BAPassword", ""));
                   }
                   else
                   {
                      API = new ZenossAPIv2(settings.getString("userName", ""), settings.getString("passWord", ""), settings.getString("URL", ""));
                   }
                }
                        
                EventObject = API.GetEvent(getIntent().getStringExtra("EventID"));*/

                if (settings.getBoolean(ZenossAPI.PREFERENCE_IS_ZAAS, false)) {
                    API = new ZenossAPIZaas();
                } else {
                    API = new ZenossAPICore();
                }

                ZenossCredentials credentials = new ZenossCredentials(ViewZenossEvent.this);
                API.Login(credentials);
                EventObject = API.GetEvent(getIntent().getStringExtra("EventID"));
            } catch (Exception e) {
                firstLoadHandler.sendEmptyMessage(0);
                BugSenseHandler.sendExceptionMessage("ViewZenossEvent", "DataPreloadThread", e);
            } finally {
                firstLoadHandler.sendEmptyMessage(1);
            }
        }
    };

    dataPreload.start();
}

From source file:com.anton.gavel.GavelMain.java

public void createDialog(int id) {
    if (progressDialog != null) {
        progressDialog.dismiss();/*  ww w.  j a v  a2  s. c o m*/
    }
    // handles creation of any dialogs by other actions
    switch (id) {
    case DIALOG_PI:
        //call custom dialog for collecting Personal Info
        PersonalInfoDialogFragment personalInfoDialog = new PersonalInfoDialogFragment();
        personalInfoDialog.setPersonalInfo(mPersonalInfo);
        personalInfoDialog.show(getSupportFragmentManager(), "PersonalInfoDialogFragment");
        break;
    case DIALOG_ABOUT:
        //construct a simple dialog to show text

        //get about text
        TextView aboutView = new TextView(this);
        aboutView.setText(R.string.about_text);
        aboutView.setMovementMethod(LinkMovementMethod.getInstance());//enable links
        aboutView.setPadding(50, 30, 50, 30);

        //build dialog
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
        alertDialog.setTitle("About")//title
                .setView(aboutView)//insert textview from above
                .setPositiveButton("Done", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                }).setIcon(R.drawable.ic_launcher).create() //build
                .show(); //display
        break;

    case DIALOG_SUBMISSION_ERR:
        AlertDialog.Builder submissionErrorDialog = new AlertDialog.Builder(this);
        submissionErrorDialog.setTitle("Submission Error")//title
                .setMessage("There was a problem submitting your complaint on the City's website.")//insert textview from above
                .setPositiveButton("Done", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                }).setIcon(R.drawable.ic_launcher).show(); //display
        break;

    case DIALOG_OTHER_COMPLAINT:
        final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        final EditText input = new EditText(this);
        input.setInputType(InputType.TYPE_TEXT_FLAG_CAP_WORDS | InputType.TYPE_CLASS_TEXT);
        // capitalize letters + seperate words
        AlertDialog.Builder getComplaintDialog = new AlertDialog.Builder(this);
        getComplaintDialog.setTitle("Other...").setView(input)
                .setMessage("Give a categorical title for your complaint:")
                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        String value = input.getText().toString();
                        // add the item to list and make it selected
                        complaintsAdapter.insert(value, 0);
                        complaintSpinner.setSelection(0);
                        complaintsAdapter.notifyDataSetChanged();
                        addToSubmitValues(value);

                        imm.toggleSoftInput(InputMethodManager.RESULT_HIDDEN, 0);//hide keyboard   
                        dialog.cancel();

                    }
                }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        imm.toggleSoftInput(InputMethodManager.RESULT_HIDDEN, 0);//hide keyboard              
                        dialog.cancel();
                    }
                }).create();

        input.requestFocus();
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);// show keyboard

        getComplaintDialog.show();//show dialog
        break;
    case DIALOG_NO_GEOCODING:
        AlertDialog.Builder noGeoCoding = new AlertDialog.Builder(this);
        noGeoCoding.setTitle("Not Available")//title
                .setMessage(
                        "Your version of Android does not support location-based address lookup. This feature is only supported on Gingerbread and above.")//insert textview from above
                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                }).setIcon(R.drawable.ic_launcher).show(); //display
        break;
    case DIALOG_INCOMPLETE_PERSONAL_INFORMATION:
        AlertDialog.Builder incompleteInfo = new AlertDialog.Builder(this);
        incompleteInfo.setTitle("Incomplete")//title
                .setMessage(
                        "Your personal information is incomplete. Select 'Edit Personal Information' from the menu and fill in all required fields")//insert textview from above
                .setPositiveButton("Done", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                }).setIcon(R.drawable.ic_launcher).show(); //display         
        break;
    case DIALOG_NO_COMPLAINT:
        AlertDialog.Builder noComplaint = new AlertDialog.Builder(this);
        noComplaint.setTitle("No Comlaint Specified")//title
                .setMessage("You must specify a complaint (e.g. barking dog).")//insert textview from above
                .setPositiveButton("Done", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                }).setIcon(R.drawable.ic_launcher).show(); //display
        break;
    case DIALOG_NO_LOCATION:
        AlertDialog.Builder incompleteComplaint = new AlertDialog.Builder(this);
        incompleteComplaint.setTitle("No Location Specified")//title
                .setMessage("You must specify a location (approximate street address) of the complaint.")//insert textview from above
                .setPositiveButton("Done", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                }).setIcon(R.drawable.ic_launcher).show(); //display         
    }

}

From source file:com.coolerfall.uiart.PagerSlidingTabStrip.java

/** add one number indicator tab */
private void addNumTab(final int position, String title, int num) {
    LinearLayout tab = new LinearLayout(getContext());
    TextView titleText = new TextView(getContext());
    TextView numText = new TextView(getContext());

    titleText.setText(title);/*from ww  w.  j a v  a  2 s . c  om*/
    titleText.setGravity(Gravity.CENTER);
    titleText.setSingleLine();

    numText.setText(Integer.toString(num));
    numText.setGravity(Gravity.CENTER);
    numText.setPadding(mNumPadding, 1, mNumPadding, 1);
    numText.setSingleLine();

    /* if the number is 0, set invisible */
    if (num == 0) {
        numText.setVisibility(View.GONE);
    } else {
        numText.setVisibility(View.VISIBLE);
    }

    tab.addView(titleText, 0, mDefaultTabLayoutParams);
    tab.addView(numText, 1, mNumLayoutParams);
    tab.setGravity(Gravity.CENTER);

    addTab(position, tab);
}

From source file:com.manning.androidhacks.hack017.CreateAccountAdapter.java

private TextView createErrorView(String key) {
    TextView ret = new TextView(mContext);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
            LayoutParams.WRAP_CONTENT);/*w  w w.  ja v  a 2s. co m*/
    params.topMargin = 10;
    params.bottomMargin = 10;
    ret.setLayoutParams(params);
    ret.setTextColor(Color.RED);
    ret.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);

    HashMap<String, String> errors = mAccount.getErrors();
    if (errors != null && errors.containsKey(key)) {
        ret.setText(errors.get(key));
        ret.setVisibility(View.VISIBLE);
    } else {
        ret.setVisibility(View.INVISIBLE);
    }

    return ret;
}

From source file:au.com.cybersearch2.classyfy.TitleSearchResultsActivityTest.java

@Test
public void test_dynamic_layout() throws Exception {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS", new Locale("en", "AU"));
    RecordCategory recordCategory = new RecordCategory();
    Date created = sdf.parse("2014-02-05 18:45:46.145000");
    Date modified = sdf.parse("2014-02-12 11:55:23.121000");
    recordCategory.setCreated(created);//from   w ww  .  ja v a 2s.  c o  m
    recordCategory.setModified(modified);
    recordCategory.setCreator("admin");
    recordCategory.setDescription("Information Technology");
    recordCategory.setIdentifier("2014-1391586274589");
    FieldDescriptor descriptionField = new FieldDescriptor();
    descriptionField.setOrder(1);
    descriptionField.setName("description");
    descriptionField.setTitle("Description");
    FieldDescriptor createdField = new FieldDescriptor();
    createdField.setOrder(2);
    createdField.setName("created");
    createdField.setTitle("Created");
    FieldDescriptor creatorField = new FieldDescriptor();
    creatorField.setOrder(3);
    creatorField.setName("creator");
    creatorField.setTitle("Creator");
    FieldDescriptor modifiedField = new FieldDescriptor();
    modifiedField.setOrder(4);
    modifiedField.setName("modified");
    modifiedField.setTitle("Modified");
    FieldDescriptor modifier = new FieldDescriptor();
    modifier.setOrder(5);
    modifier.setName("modifier");
    modifier.setTitle("Modifier");
    FieldDescriptor identifierField = new FieldDescriptor();
    identifierField.setOrder(6);
    identifierField.setName("identifier");
    identifierField.setTitle("Identifier");
    Set<FieldDescriptor> fieldSet = new TreeSet<FieldDescriptor>();
    fieldSet.add(descriptionField);
    fieldSet.add(createdField);
    fieldSet.add(creatorField);
    fieldSet.add(modifiedField);
    fieldSet.add(modifier);
    fieldSet.add(identifierField);
    @SuppressWarnings("unchecked")
    Map<String, Object> valueMap = PropertyUtils.describe(recordCategory);
    titleSearchResultsActivity = (TitleSearchResultsActivity) controller.create().get();
    LinearLayout dynamicLayout = new LinearLayout(titleSearchResultsActivity);
    dynamicLayout.setOrientation(LinearLayout.VERTICAL);
    int layoutHeight = LinearLayout.LayoutParams.MATCH_PARENT;
    int layoutWidth = LinearLayout.LayoutParams.WRAP_CONTENT;
    for (FieldDescriptor descriptor : fieldSet) {
        Object value = valueMap.get(descriptor.getName());
        if (value == null)
            continue;
        TextView titleView = new TextView(titleSearchResultsActivity);
        titleView.setText(descriptor.getTitle());
        TextView valueView = new TextView(titleSearchResultsActivity);
        valueView.setText(value.toString());
        LinearLayout fieldLayout = new LinearLayout(titleSearchResultsActivity);
        fieldLayout.setOrientation(LinearLayout.HORIZONTAL);
        fieldLayout.addView(titleView, new LinearLayout.LayoutParams(layoutWidth, layoutHeight));
        fieldLayout.addView(valueView, new LinearLayout.LayoutParams(layoutWidth, layoutHeight));
    }
}

From source file:com.QuarkLabs.BTCeClient.fragments.HomeFragment.java

/**
 * Refreshes funds table with fetched data
 *
 * @param response JSONObject with funds data
 *//*from ww  w.  jav a2  s . co m*/
private void refreshFunds(JSONObject response) {
    try {
        if (response == null) {
            Toast.makeText(getActivity(), getResources().getString(R.string.GeneralErrorText),
                    Toast.LENGTH_LONG).show();
            return;
        }
        String notificationText;
        if (response.getInt("success") == 1) {

            View.OnClickListener fillAmount = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ScrollView scrollView = (ScrollView) getView();
                    if (scrollView != null) {
                        EditText tradeAmount = (EditText) scrollView.findViewById(R.id.TradeAmount);
                        tradeAmount.setText(((TextView) v).getText());
                        scrollView.smoothScrollTo(0, scrollView.findViewById(R.id.tradingSection).getBottom());
                    }
                }
            };

            notificationText = getResources().getString(R.string.FundsInfoUpdatedtext);
            TableLayout fundsContainer = (TableLayout) getView().findViewById(R.id.FundsContainer);
            fundsContainer.removeAllViews();
            JSONObject funds = response.getJSONObject("return").getJSONObject("funds");
            JSONArray fundsNames = response.getJSONObject("return").getJSONObject("funds").names();
            List<String> arrayList = new ArrayList<>();

            for (int i = 0; i < fundsNames.length(); i++) {
                arrayList.add(fundsNames.getString(i));
            }
            Collections.sort(arrayList);
            TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(0,
                    ViewGroup.LayoutParams.MATCH_PARENT, 1);

            for (String anArrayList : arrayList) {

                TableRow row = new TableRow(getActivity());
                TextView currency = new TextView(getActivity());
                TextView amount = new TextView(getActivity());
                currency.setText(anArrayList.toUpperCase(Locale.US));
                amount.setText(funds.getString(anArrayList));
                currency.setLayoutParams(layoutParams);
                currency.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
                currency.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
                currency.setGravity(Gravity.CENTER);
                amount.setLayoutParams(layoutParams);
                amount.setGravity(Gravity.CENTER);
                amount.setOnClickListener(fillAmount);
                row.addView(currency);
                row.addView(amount);
                fundsContainer.addView(row);
            }

        } else {
            notificationText = response.getString("error");
        }

        mCallback.makeNotification(ConstantHolder.ACCOUNT_INFO_NOTIF_ID, notificationText);

    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:com.farmerbb.notepad.fragment.NoteViewFragment.java

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override//from   www. j  av  a2 s. c o m
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    // Set values
    setRetainInstance(true);
    setHasOptionsMenu(true);

    // Get filename of saved note
    filename = getArguments().getString("filename");

    // Change window title
    String title;

    try {
        title = listener.loadNoteTitle(filename);
    } catch (IOException e) {
        title = getResources().getString(R.string.view_note);
    }

    getActivity().setTitle(title);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        Bitmap bitmap = ((BitmapDrawable) ContextCompat.getDrawable(getActivity(), R.drawable.ic_recents_logo))
                .getBitmap();

        ActivityManager.TaskDescription taskDescription = new ActivityManager.TaskDescription(title, bitmap,
                ContextCompat.getColor(getActivity(), R.color.primary));
        getActivity().setTaskDescription(taskDescription);
    }

    // Show the Up button in the action bar.
    ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // Animate elevation change
    if (getActivity().findViewById(R.id.layoutMain).getTag().equals("main-layout-large")
            && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        LinearLayout noteViewEdit = getActivity().findViewById(R.id.noteViewEdit);
        LinearLayout noteList = getActivity().findViewById(R.id.noteList);

        noteList.animate().z(0f);
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
            noteViewEdit.animate()
                    .z(getResources().getDimensionPixelSize(R.dimen.note_view_edit_elevation_land));
        else
            noteViewEdit.animate().z(getResources().getDimensionPixelSize(R.dimen.note_view_edit_elevation));
    }

    // Set up content view
    TextView noteContents = getActivity().findViewById(R.id.textView);
    markdownView = getActivity().findViewById(R.id.markdownView);

    // Apply theme
    SharedPreferences pref = getActivity().getSharedPreferences(getActivity().getPackageName() + "_preferences",
            Context.MODE_PRIVATE);
    ScrollView scrollView = getActivity().findViewById(R.id.scrollView);
    String theme = pref.getString("theme", "light-sans");
    int textSize = -1;
    int textColor = -1;

    String fontFamily = null;

    if (theme.contains("light")) {
        if (noteContents != null) {
            noteContents.setTextColor(ContextCompat.getColor(getActivity(), R.color.text_color_primary));
            noteContents.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background));
        }

        if (markdownView != null) {
            markdownView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background));
            textColor = ContextCompat.getColor(getActivity(), R.color.text_color_primary);
        }

        scrollView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background));
    }

    if (theme.contains("dark")) {
        if (noteContents != null) {
            noteContents.setTextColor(ContextCompat.getColor(getActivity(), R.color.text_color_primary_dark));
            noteContents
                    .setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background_dark));
        }

        if (markdownView != null) {
            markdownView
                    .setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background_dark));
            textColor = ContextCompat.getColor(getActivity(), R.color.text_color_primary_dark);
        }

        scrollView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background_dark));
    }

    if (theme.contains("sans")) {
        if (noteContents != null)
            noteContents.setTypeface(Typeface.SANS_SERIF);

        if (markdownView != null)
            fontFamily = "sans-serif";
    }

    if (theme.contains("serif")) {
        if (noteContents != null)
            noteContents.setTypeface(Typeface.SERIF);

        if (markdownView != null)
            fontFamily = "serif";
    }

    if (theme.contains("monospace")) {
        if (noteContents != null)
            noteContents.setTypeface(Typeface.MONOSPACE);

        if (markdownView != null)
            fontFamily = "monospace";
    }

    switch (pref.getString("font_size", "normal")) {
    case "smallest":
        textSize = 12;
        break;
    case "small":
        textSize = 14;
        break;
    case "normal":
        textSize = 16;
        break;
    case "large":
        textSize = 18;
        break;
    case "largest":
        textSize = 20;
        break;
    }

    if (noteContents != null)
        noteContents.setTextSize(textSize);

    String css = "";
    if (markdownView != null) {
        String topBottom = " " + Float.toString(getResources().getDimension(R.dimen.padding_top_bottom)
                / getResources().getDisplayMetrics().density) + "px";
        String leftRight = " " + Float.toString(getResources().getDimension(R.dimen.padding_left_right)
                / getResources().getDisplayMetrics().density) + "px";
        String fontSize = " " + Integer.toString(textSize) + "px";
        String fontColor = " #" + StringUtils.remove(Integer.toHexString(textColor), "ff");
        String linkColor = " #" + StringUtils.remove(
                Integer.toHexString(new TextView(getActivity()).getLinkTextColors().getDefaultColor()), "ff");

        css = "body { " + "margin:" + topBottom + topBottom + leftRight + leftRight + "; " + "font-family:"
                + fontFamily + "; " + "font-size:" + fontSize + "; " + "color:" + fontColor + "; " + "}"
                + "a { " + "color:" + linkColor + "; " + "}";

        markdownView.getSettings().setJavaScriptEnabled(false);
        markdownView.getSettings().setLoadsImagesAutomatically(false);
        markdownView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                    try {
                        startActivity(intent);
                    } catch (ActivityNotFoundException | FileUriExposedException e) {
                        /* Gracefully fail */ }
                else
                    try {
                        startActivity(intent);
                    } catch (ActivityNotFoundException e) {
                        /* Gracefully fail */ }

                return true;
            }
        });
    }

    // Load note contents
    try {
        contentsOnLoad = listener.loadNote(filename);
    } catch (IOException e) {
        showToast(R.string.error_loading_note);

        // Add NoteListFragment or WelcomeFragment
        Fragment fragment;
        if (getActivity().findViewById(R.id.layoutMain).getTag().equals("main-layout-normal"))
            fragment = new NoteListFragment();
        else
            fragment = new WelcomeFragment();

        getFragmentManager().beginTransaction().replace(R.id.noteViewEdit, fragment, "NoteListFragment")
                .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).commit();
    }

    // Set TextView contents
    if (noteContents != null)
        noteContents.setText(contentsOnLoad);

    if (markdownView != null)
        markdownView.loadMarkdown(contentsOnLoad,
                "data:text/css;base64," + Base64.encodeToString(css.getBytes(), Base64.DEFAULT));

    // Show a toast message if this is the user's first time viewing a note
    final SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    firstLoad = sharedPref.getInt("first-load", 0);
    if (firstLoad == 0) {
        // Show dialog with info
        DialogFragment firstLoad = new FirstViewDialogFragment();
        firstLoad.show(getFragmentManager(), "firstloadfragment");

        // Set first-load preference to 1; we don't need to show the dialog anymore
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putInt("first-load", 1);
        editor.apply();
    }

    // Detect single and double-taps using GestureDetector
    final GestureDetector detector = new GestureDetector(getActivity(),
            new GestureDetector.OnGestureListener() {
                @Override
                public boolean onSingleTapUp(MotionEvent e) {
                    return false;
                }

                @Override
                public void onShowPress(MotionEvent e) {
                }

                @Override
                public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                    return false;
                }

                @Override
                public void onLongPress(MotionEvent e) {
                }

                @Override
                public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                    return false;
                }

                @Override
                public boolean onDown(MotionEvent e) {
                    return false;
                }
            });

    detector.setOnDoubleTapListener(new GestureDetector.OnDoubleTapListener() {
        @Override
        public boolean onDoubleTap(MotionEvent e) {
            if (sharedPref.getBoolean("show_double_tap_message", true)) {
                SharedPreferences.Editor editor = sharedPref.edit();
                editor.putBoolean("show_double_tap_message", false);
                editor.apply();
            }

            Bundle bundle = new Bundle();
            bundle.putString("filename", filename);

            Fragment fragment = new NoteEditFragment();
            fragment.setArguments(bundle);

            getFragmentManager().beginTransaction().replace(R.id.noteViewEdit, fragment, "NoteEditFragment")
                    .commit();

            return false;
        }

        @Override
        public boolean onDoubleTapEvent(MotionEvent e) {
            return false;
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            if (sharedPref.getBoolean("show_double_tap_message", true) && showMessage) {
                showToastLong(R.string.double_tap);
                showMessage = false;
            }

            return false;
        }

    });

    if (noteContents != null)
        noteContents.setOnTouchListener((v, event) -> {
            detector.onTouchEvent(event);
            return false;
        });

    if (markdownView != null)
        markdownView.setOnTouchListener((v, event) -> {
            detector.onTouchEvent(event);
            return false;
        });
}

From source file:com.adamkruger.myipaddressinfo.NetworkInfoFragment.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private TextView makeTextView(String value, int color, int horizontalPadding) {
    Context context = getActivity();
    TextView textView = new TextView(context);
    textView.setText(value);//from   w  ww  .  j  a va 2 s.  co m
    textView.setLayoutParams(
            new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
    textView.setTextAppearance(context, android.R.attr.textAppearanceSmall);
    textView.setTextColor(color);
    textView.setPadding(horizontalPadding, 0, horizontalPadding, 0);
    textView.setSingleLine(false);
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
        textView.setTextIsSelectable(true);
    }
    return textView;
}

From source file:com.github.wakhub.monodict.activity.FlashcardActivity.java

@UiThread
void showAutoPlayAlertDialog() {
    if (autoPlayDialog != null) {
        return;//from w ww .j  ava 2 s  .c  om
    }

    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);
    layout.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT));
    layout.setPadding(20, 20, 20, 20);
    autoPlayDisplayText = new TextView(this);
    autoPlayDisplayText.setTypeface(Typeface.DEFAULT_BOLD);
    layout.addView(autoPlayDisplayText);
    autoPlayTranslateText = new TextView(this);
    autoPlayTranslateText.setText(R.string.message_in_processing);
    layout.addView(autoPlayTranslateText);

    autoPlayDialog = new AlertDialog.Builder(this).setTitle(R.string.action_auto_play)
            .setIcon(R.drawable.ic_action_play).setView(layout)
            .setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialogInterface) {
                    autoPlayDisplayText = null;
                    autoPlayTranslateText = null;
                    stopAutoPlay();
                }
            }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.cancel();
                }
            }).show();
}