package com.eni.android.textwatcher;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class TextWatcherEjemplo extends Activity implements
TextWatcher {

	private EditText msg;
	private TextView textIndicator;
	private Button send;

	private final static int NUMMAXCHAR = 20;

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		msg = (EditText) findViewById(R.id.msg);
		msg.addTextChangedListener(this);
		textIndicator = (TextView) findViewById(R.id.indicator);
		send = (Button) findViewById(R.id.send);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.text_watcher_ejemplo, menu);
		return true;
	}
	
	@Override
	public void afterTextChanged(Editable s) {
		int numChar = msg.getText().toString().length();
		int leftChar = NUMMAXCHAR - numChar;
		if (leftChar >= 0) {
			textIndicator.setText(Integer.toString(leftChar)
					+ getString(R.string._caract_restantes));
			textIndicator.setTextColor(Color.GREEN);
			send.setEnabled(true);
		} else {
			textIndicator.setTextColor(Color.RED);
			textIndicator.setText(Integer.toString(Math.abs(leftChar))
					+ getString(R.string._caract_exceso));
			send.setEnabled(false);
		}

	}

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

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