Created
December 6, 2014 15:17
-
-
Save LarsEliasNielsen/c1e96a491e952e542b5a to your computer and use it in GitHub Desktop.
Playing with Android TextWatcher
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.coursera.four; | |
import android.graphics.Bitmap; | |
import android.graphics.Canvas; | |
import android.graphics.Color; | |
import android.graphics.Paint; | |
import android.os.Bundle; | |
import android.support.v7.app.ActionBarActivity; | |
import android.text.Editable; | |
import android.text.TextWatcher; | |
import android.view.Display; | |
import android.widget.EditText; | |
import android.widget.ImageView; | |
import android.widget.TextView; | |
public class TextWatcherActivity extends ActionBarActivity { | |
TextView reverseTextView; | |
Display metrics; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_text_watcher); | |
// Old up navigation for activity. | |
getSupportActionBar().setDisplayHomeAsUpEnabled(true); | |
// Get EditText and add TextWatcher. | |
EditText editText = (EditText) findViewById(R.id.edit_text_watcher); | |
editText.addTextChangedListener(watcher); | |
// Get TextView for reversed text. | |
reverseTextView = (TextView) findViewById(R.id.inverse_text); | |
} | |
TextWatcher watcher = new TextWatcher() { | |
@Override | |
public void afterTextChanged(Editable arg0) { | |
// Nothing to see here. | |
} | |
@Override | |
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { | |
// Move along. | |
} | |
@Override | |
public void onTextChanged(CharSequence s, int a, int b, int c) { | |
// Get display metrics. | |
metrics = getWindowManager().getDefaultDisplay(); | |
// Get watcher text as String. | |
String text = s.toString(); | |
// Reverse text and add to TextView. | |
String inversedText = new StringBuilder(s).reverse().toString(); | |
reverseTextView.setText(inversedText); | |
// Create a canvas with same width as screen. | |
// TODO: It may not be a good idea to create the complete canvas each time. | |
Bitmap bitmap = Bitmap.createBitmap(metrics.getWidth(), 200, Bitmap.Config.ARGB_8888); | |
Canvas canvas = new Canvas(bitmap); | |
// Paint some cyan text on the canvas. | |
Paint paint = new Paint(); | |
canvas.drawPaint(paint); | |
paint.setColor(Color.CYAN); | |
paint.setTextSize(28); | |
canvas.drawText(text, 10, 25, paint); | |
// Add the canvas to the ImageView. | |
ImageView canvasImageView = (ImageView) findViewById(R.id.canvas_image_view); | |
canvasImageView.setImageBitmap(bitmap); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment