How to display cursor at the end of text in TextView? - android

I wanted to display blinking cursor at the end of the text in TextView .
I tried by android:cursorVisible="true" in TextView But no go .
Even i tried text.setCursorVisible(true); Doesn't work .
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:cursorVisible="true"
android:textCursorDrawable="#null" />
Does any one know any solution for it ?

First of all you should use EditText in place of TextView for taking input. If still the cursor doesn't blink, set the android:cursorVisible="true"attribute in xml file, it should make the cursor blink. If your cursor is not visible in edit text, that's also a reason one can't see the cursor blinking. Set android:textCursorDrawable="#null". This should solve your problem
<EditText
android:id="#+id/editext1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textCursorDrawable="#null"
android:cursorVisible="true">
</EditText>
In your activity class, add this code as well.
EditText input = (EditText)findViewById(R.id.edittext1);
input.setSelection(input.getText().length());

There is a solution for this.
I had to do this when I was making a terminal app and I used a simple runnable put a cursor at the end and make it blink.
I made 3 class variables:
private boolean displayCursor;
private boolean cursorOn;
private String terminalText;
private TextView terminal; // The TextView Object
terminalText keeps track of the text to be displayed.
Created a class method that runs the runnable the first time
private void runCursorThread() {
Runnable runnable = new Runnable() {
public void run() {
if (displayCursor) {
if (cursorOn) {
terminal.setText(terminalText);
} else {
terminal.setText(terminalText + '_');
}
cursorOn = !cursorOn;
}
terminal.postDelayed(this, 400);
}
};
runnable.run();
}
And initiated the variables and called runCursorThread() in onCreate()
cursorOn = false;
displayCursor = true;
runCursorThread();

I think you should go for EditText. You can set its background and make it appears like TextView with below code.
Step 1
<EditText
android:id="#+id/edtText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent" >
</EditText>
Step 2
EditText edt = (EditText) findViewById(R.id.edtText);
edt.setSelection(edt.getText().length());
Output

Finally Fixed this Using the EditText as per #Chintan Rathod advice.
<EditText
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/transparent"/> //reference to #Chintan Rathod.
Code
EditText text=(EditText) findViewById(R.id.text);
text.setText("hello");
text.setSelection(text.getText().length()); // reference to #Umer Farooq code.

Related

Android EditText .setText("") not working

I am trying to clear the text in my edit text field but for some reason it is not working.
I have declared an edit text field in the xml of my view:
<EditText
android:id="#+id/enterGlucoseLevel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/mySimpleXYPlot"
android:layout_centerHorizontal="true"
android:ems="10"
android:inputType="numberDecimal" />
I have used the attribute onClick to link my button to the enterGlucoseAction() method in my MainActivity class:
<Button
android:id="#+id/enterGlucoseButton"
android:clickable="true"
android:onClick= "enterGlucoseAction"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/enterGlucoseLevel"
android:layout_centerHorizontal="true"
android:text="#string/enterGlucoseLvlButton" />
Here is that method:
public void enterGlucoseAction(View v) {
glucoseField.setText("");
Toast.makeText(v.getContext(), "You clicked the button", Toast.LENGTH_SHORT).show();
}
I get the toast pop up but my edit text field is not being cleared.
Here is my on create and instance variables in case the problem lies there.
private XYPlot plot;
private Button addGlucoseLevel;
private EditText glucoseField;
private XYSeries currentSeries;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addGlucoseLevel = (Button) findViewById(R.id.enterGlucoseButton);
glucoseField = (EditText) findViewById(R.id.enterGlucoseLevel);
currentSeries = new SimpleXYSeries(Arrays.asList(new Number[] { 7200, 8, 54000, 2, 64800, 4 }),
SimpleXYSeries.ArrayFormat.XY_VALS_INTERLEAVED,
"Glucose Level");
//Create an series of numbers to plot.
createGraph(currentSeries);
}
Thanks in advance.
And sorry, I know this has been asked before but I can't find a solution to my problem specifically.
To clear your EditText which accepts numbers use clear() method:
glucoseField.getText().clear();
You can try setting it this way:
((EditText)findViewById(R.id.enterGlucoseLevel)).getText().clear();
Alternatively you can use getText().clear(); just replace glucoseField.setText(""); with glucoseField.getText().clear();
You should use
setText("\b");
As we can use escape sequence
((EditText)findViewById(R.id.yourEditTextId)).getText().clear();
anything else crashed.

Hide text only but not whole textview

My goal to hide text and keep textview occupying its space in the activity , i set already my text to be invisible by using :
tv.setVisibility(View.INVISIBLE);
and when button clicked it show the text , every thing work fine except the result of my code lead to hide whole textview not only the text , because i set my textview background to drawable shape which form red border around the text as:
android:background="#drawable/border1"
<TextView
android:id="#+id/introclusion_tv3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/border1"
android:textSize="20sp" />
when start app you can see empty space only which will be fill with text after button click but there's no border there (which come from shape background) , so it hide whole textview and i need it to hide only text and keep the textview with its background shown when text set to INVISIBLE,
any help will be really appreciated ,thanks.
this is how i did it:
TextView tv11=(TextView)findViewById(R.id.introclusion_tv3);
tv11.setText(Html.fromHtml(getString(R.string.introclusion_one)));
tv11.setVisibility(View.INVISIBLE);
then after click the but and write correct password it show the text as:
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
dialogButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
EditText password = (EditText) dialog.findViewById(R.id.password);
if( password.getText().toString().length() > 0 ) {
if( password.getText().toString().equals("test")) {
TextView tv11=(TextView)findViewById(R.id.introclusion_tv3);
tv11.setTypeface(FontFactory.getBFantezy(getBaseContext()));
tv11.setText(Html.fromHtml(getString(R.string.introclusion_one)));
tv11.setVisibility(View.VISIBLE);
}
Transparent text color hides the text:
<TextView
android:id="#+id/introclusion_tv3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/border1"
android:textColor="#android:color/transparent"
android:textSize="20sp" />
When you want to show your text, change the text color programmatically using method setTextColor():
tv11.setTextColor(color);
// try this way
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/border1">
<TextView
android:id="#+id/introclusion_tv3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp" />
</LinearLayout>
you can make simple trick : write two string
lets say in your first and second piece of code just remove this line
tv11.setVisibility(View.INVISIBLE);
and
tv11.setVisibility(View.VISIBLE);
so it will be
TextView tv11=(TextView)findViewById(R.id.introclusion_tv3);
tv11.setText(Html.fromHtml(getString(R.string.introclusion_one)));
then in second piece write as follow ;
if( password.getText().toString().equals("test")) {
TextView tv11=(TextView)findViewById(R.id.introclusion_tv3);
tv11.setTypeface(FontFactory.getBFantezy(getBaseContext()));
tv11.setText(Html.fromHtml(getString(R.string.introclusion_one_appear)));
}
where first string will be empty
<string name="introclusion_one">
and second string you will write your text in it
<string name="introclusion_one_appear">
Hope help you .
save what is in the text view as a string like this:
String x = (String)tv11.getText();
then make the text view empty like this:
String x = "";
for(int i = 0; i < x.length(); i++){
x +=" ";
}
tv11.setText(x);
to make the textview visible again do:
tv11.setText(x);

android.widget.Button cannot be cast to android.widget.EditText

Developing my first Android calculator application, I succeeded in updating a TextView in a new activity by passing the answer via an intent, but this requires the user to hit Back to perform another calculation. I'm trying to make the doCalculation button update a simple TextView in the MainActivity and getting the error:
06-22 11:08:17.318: E/AndroidRuntime(31328): Caused by: java.lang.ClassCastException: android.widget.Button cannot be cast to android.widget.EditText
Here's my code:
/** Called when the user clicks the Calculate! button */
public void doCalculation(View view) {
// Do something in response to button
int answerInt;
String answer;
EditText numberOne = (EditText) findViewById(R.id.number1);
EditText numberTwo = (EditText) findViewById(R.id.number2);
int numberOnee = Integer.parseInt(numberOne.getText().toString());
int numberTwoo = Integer.parseInt(numberTwo.getText().toString());
answerInt = numberOnee * numberTwoo;
answer = Integer.toString(answerInt);
TextView homeAnswerView = (TextView) findViewById(R.id.homeAnswerView);
homeAnswerView.setTextSize(40);
homeAnswerView.setText(answer);
}
For reference, here's the code that worked successfully launching a new activity:
// Called when the user clicks the Calculate! button
public void doCalculation(View view) {
// Do something in response to button
int answerInt;
String answer;
Intent intent = new Intent(this, DisplayCalculationActivity.class);
EditText numberOne = (EditText) findViewById(R.id.number1);
EditText numberTwo = (EditText) findViewById(R.id.number2);
int numberOnee = Integer.parseInt(numberOne.getText().toString());
int numberTwoo = Integer.parseInt(numberTwo.getText().toString());
answerInt = numberOnee * numberTwoo;
answer = Integer.toString(answerInt);
intent.putExtra(EXTRA_MESSAGE, answer);
startActivity(intent);
}
UPDATE, the XML for reference:
<EditText
android:id="#+id/number2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView3"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:ems="10"
android:inputType="number" />
<EditText
android:id="#+id/number1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:ems="10"
android:inputType="number"
android:singleLine="true" />
<Button
android:id="#+id/calculateBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/number2"
android:layout_alignRight="#+id/number2"
android:layout_below="#+id/number2"
android:layout_marginTop="14dp"
android:onClick="doCalculation"
android:text="Calculate!" />
Thank you for your help,
-Michael
It seems like either R.id.number1 or R.id.number2 is a Button. Check your XML and make sure it's an EditText.
Edit: Original answer didn't work, but cleaning the project solved the problem.
I've just had this problem. It seems that the xml layout file is not compiled properly. Or rather it is not included in the list of changed files to be compiled.
i was having the same situation but i found out that there are two textviews with same ids in different activities so i changed one of them and the program ran clearly so check the ids of all your edittext and buttons and change the samilier even if they were in other activities and i think it will run with out any problems
I followed the steps in the answer (cleaned and then made sure it's the id) and noticed that going to the source of my EditText R.id brings me to the EditText. Thought this is definitely not a IDE cache problem.
What I did do is to change the LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
to
android:layout_width="match_parent"
android:layout_height="match_parent"
For some reason it fixed the issue (I had this whole layout wrapped in something else that I just recently removed).

Android Move cursor from one EditText to another one?

I know these type of question asked many time .but still nobody gave perfect answer for that.
I have question :
I want to move from EditText1 ** to another **EditText2 .
I had already detect to editText1 but how to move cursor to editText2.?
In short I had to move my cursor position from one editText1 to another EditText2 directly.
I faced this type of issue and found the solution as below.
Here I have two editText, if I press "a", my cursor will move to next step. I used below code for doing it.
final EditText editText = (EditText) findViewById(R.id.editText1);
editText.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v , int keyCode , KeyEvent event) {
EditText editText2 = (EditText) findViewById(R.id.editText2);
// TODO Auto-generated method stub
if (keyCode == event.KEYCODE_A) {
Selection.setSelection((Editable) editText2.getText(),editText.getSelectionStart());
editText2.requestFocus();
}
return true;
}
});
Let me know if you are facing any error regarding this.
For this, all you need to do is...add below two properties to your EditText tag in xml, except the last EditText(In case, you add it to the last EditText also, then the cursor control will again go to the first EditText when you press enter/next from the keypad)
<EditText
.
.
android:singleLine="true"
android:imeOptions="actionNext"
.
.
/>
Hope this helps
Here is a working example, hope this helps.
XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:id="#android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Some string of text"
/>
<EditText
android:id="#android:id/text2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Some string of text"
/>
<Button
android:id="#android:id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button"
/>
</LinearLayout>
Class:
public class Example extends Activity {
TextView text1;
TextView text2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text1 = (EditText) findViewById(android.R.id.text1);
text2 = (EditText) findViewById(android.R.id.text2);
Button button = (Button) findViewById(android.R.id.button1);
button.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Selection.setSelection((Editable) text2.getText(), text1.getSelectionStart());
text2.requestFocus();
}
});
}
}
Set onKeyListener to detect the key pressed on every key pressed checked your condition and when your condition will be fulfilled set edittext property edittext2.requestFocus();
I have tested all the previous code segments, and find all are working fine. But I find just calling "requestFocus()" with the proper edittext object is also working. As per as ques asked, the ans can be:
edittext2.requestFocus();
which is working fine for me. Please correct me if I am wrong.

setGravity not working

Please see my code below. I am unable to make SetGravity work.
How come?
Layout Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="25dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:longClickable="true"
android:orientation="vertical" >
<EditText
android:id="#+id/etCommands"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Type a command"
android:password="true" />
<LinearLayout
android:weightSum="100"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_weight="20"
android:id="#+id/btnResults"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Results" />
<ToggleButton
android:paddingBottom="10dp"
android:layout_weight="80"
android:id="#+id/passTog"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="ToggleButton" android:checked="true"/>
</LinearLayout>
<TextView
android:id="#+id/tvResults"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="invalid" />
</LinearLayout>
java code:
public class TextPlay extends Activity {
private static final String TAG = "MyApp";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
Button chkCmd = (Button) findViewById(R.id.btnResults);
final ToggleButton passTog = (ToggleButton) findViewById(R.id.passTog);
final EditText input = (EditText) findViewById(R.id.etCommands);
final TextView display = (TextView) findViewById(R.id.tvResults);
passTog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (passTog.isChecked()) {
input.setInputType(InputType.TYPE_CLASS_TEXT
| InputType.TYPE_TEXT_VARIATION_PASSWORD);
} else {
input.setInputType(InputType.TYPE_CLASS_TEXT);
}
}
});
chkCmd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String check = input.getText().toString();
Log.i(TAG, "Check Value is: " + check);
if (check.contentEquals("left")) {
Log.i(TAG, "I am under left ");
display.setGravity(Gravity.LEFT); //WHYW ILL YOU NOT WORK SETGRAVITY?????????????
} else if (check.contentEquals("center")) {
display.setGravity(Gravity.CENTER);
} else if (check.contentEquals("right")) {
display.setGravity(Gravity.RIGHT);
}
else if (check.contentEquals("blue")) {
display.setGravity(Gravity.RIGHT);
}
}
});
}
}
I just tested and it works.. You might be doing a few things wrong;
First of all, when you type "left" into the text field, are you making sure that you didn't type "Left" (most keyboards capitalize the first letter)
If you are sure about the above, do you see the log that says "I am under left " (Not the "Check is")? If not, then it's not getting there somehow..
If you are indeed seeing it, you might want to clean/build your project (in Eclipse Project-> Clean -it does cleaning and re-building)
If that doesn't work neither, you might want to change your target build (change it to API level 10 or so) You don't really need to worry about the target build if you are just using this as an exercise to learn.
I think we're not able to change UI this way.
I usually do like this.
TableLayout table1 = (TableLayout) findViewById(R.id.table1);
txtresult.setGravity(Gravity.RIGHT);
((TableLayout) table1).addView(txtresult);
It works with me.
So I suggest you to do a trick like delete that TextView "display" and generate a new one with new Gravity properties.
Hope it works!
Linh
Try to set layout_gravity="center" and layout_width="wrap_ontent" maybe that will do it :)
set layout_width="wrap_content" and set the layout gravity.
Have you tried to call invalidate after you change the layout attribute of your text view?
Android Documentation - View.invalidate()
Change the conditions as below:
check.equalsIgnoreCase("left")
Hope this solves ur problem.
View.invalidate() must be involved on UI thread. If you are doing the view re-configuration within a Listener callback which is your case, then you probably need call View.postInvalidate(), check out the API:
public void invalidate ()
Since: API Level 1
Invalidate the whole view. If the view is visible, onDraw(android.graphics.Canvas) will be called at some point in the future. This must be called from a UI thread. To call from a non-UI thread, call postInvalidate().
Try this:
<LinearLayout
android:id="#+id/llResults"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center">
<TextView
android:id="#+id/tvResults"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="invalid" />
</LinearLayout>
Instead of Doing :- tvResults.setGravity
try setting gravity of linearlayout :- llResults.setGravity
your code works good for me, i´ve tested on a real device with android 4.0.3 (Nexus S), the only thing that can be bothering you its capital letters as #Tolga E told.
you can try:
check.equalsIgnoreCase("left")
instead of:
check.contentEquals("left")
and debugging, put a breakpoint on the if´s to check that your code is actually trying to modify the gravity or its skipping that line.
Hope it helps.
If anyone who's following thenewboston's tutorial stumbles upon this with the same problem, it's an issue with the display variable. Just change
final TextView display = (TextView) findViewById(R.id.tvDisplay);
to
final TextView display = (TextView) findViewById(R.id.tvResults);
up with the other variable declarations.
I think setGravity method has been depreciated from API 4.0 . I don't see any alternative. Only way left you need to use API level 8.0. I am also getting nulpointer exceptions in log cat by using setGravity method
Set your TextView's width as android:layout_width="fill_parent"then you can set it programmatically using myTextView.setGravity(Gravity.CENTER) .

Categories

Resources