I have one edittext. First time my edittext's settext is 1 and I want to clear this text in editttext click and input new keyboard values
I wrote code but not working
price_counter = (EditText) rootView
.findViewById(R.id.strada_price_counter);
price_counter.setText("1");
price_counter.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
price_counter.setText("");
}
});
<EditText
android:id="#+id/strada_price_counter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/strada_buy_btn"
android:layout_marginLeft="18dp"
android:layout_toRightOf="#+id/strada_buy_btn"
android:background="#drawable/input_value"
android:gravity="center"
android:inputType="number">
</EditText>
this code not working if anyone knows solution please help me
You are not supposed to call setOnClickListener on EditText. Register click listener for a button and call settext for EditText on button click.
Update your code to the following:
price_counter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((EditText)v).setText("");
}
});
Try this code... This might be you are looking for
public class MainActivity extends Activity implements OnTouchListener
{
EditText et;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et=(EditText)findViewById(R.id.editText1);
et.setText("1");
et.setOnTouchListener(this);
}
#Override
public boolean onTouch(View v, MotionEvent event)
{
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
et.setText("");
}
return false;
}
}
Related
I have a number of EditText elements in my page along with two buttons. I want the user to touch on any one EditText field and click any button to insert a certain value into that very EditText field they touched. Giving input using the keypad is not allowed. Please help me to do this.
You can use View.OnFocusChangeListener to detect if any view (edittext) gained or lost focus.
for (EditText view : editList){
view.setOnFocusChangeListener(focusListener);
}
....
private OnFocusChangeListener focusListener = new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus){
focusedView = v;
} else {
focusedView = null;
}
}
}
This goes in your activity or fragment or wherever you have the EditTexts. The .... is just saying that you can put it anywhere else in the class. And obviously you would need to create an array with them in it, thus the editList.
This works for me. It returns a boolean.
myEditText.hasFocus()
One thing that you can do is declare a global variable evalue which will tell you which is the last selected EditText by using onTouchListener and then based on the value of evalue, you can set the text value to the edittext by button click. hope you understood.
the code for it can be as follow:
EditText e1,e2;
Button b1,b2;
String evalue;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
e1=(EditText)findViewById(R.id.editText1);
e2=(EditText)findViewById(R.id.editText2);
b1=(Button)findViewById(R.id.button1);
b2=(Button)findViewById(R.id.button2);
e1.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View arg0, MotionEvent arg1)
{
evalue="1";
return false;
}
});
e2.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View arg0, MotionEvent arg1)
{
evalue="2";
return false;
}
});
b1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0) {
if(evalue=="1")
{
e1.setText("yes");
}
if(evalue=="2")
{
e2.setText("yes");
}
}
});
b2.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0) {
if(evalue=="1")
{
e1.setText("No");
}
if(evalue=="2")
{
e2.setText("No");
}
}
});
}
Its a logical coding.. not upto the mark.. if you find a better one. then use it. thank you.
This worked for me.
e1 = (EditText) findViewById(R.id.editText1);
e1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View arg0, boolean hasfocus) {
if (hasfocus) {
Log.e("TAG", "e1 focused")
} else {
Log.e("TAG", "e1 not focused")
}
}
});
With Java 8 lambdas:
EditText editTextTo = findViewById(R.id.editTextTo);
editTextTo.setOnFocusChangeListener((view, b) -> {
if (view.isFocused()) {
// Do whatever you want when the EditText is focused
// Example:
editTextFrom.setText("Focused!");
}
});
Note that the view inside the lambda function is actually an instance of an EditText.
Have your Fragment implement OnTouchListener & OnFocusChangeListener:
public class AttributesFragment extends Fragment
implements OnTouchListener, OnFocusChangeListener {
Then implement using:
#Override
public boolean onTouch(View view, MotionEvent event) {
if (view instanceof EditText) {
view.setOnFocusChangeListener(this); // User touched edittext
}
return false;
}
#Override
public void onFocusChange(View v, boolean hasFocus) {
}
Don't forget to set your listener after creating your EditText
editText.setOnTouchListener(this);
This way if an EditText box is focused by default but user has not changed the field it will not fire the onFocusChange event.
Simple Coding:
if(EditText1.isFocused()){
//EditText1 is focused
}else if(EditText2.isFocused()){
//EditText2 is focused
}
This worked for me using Java 8 (lambdas):
EditText myEditText = findViewById(R.id.editText);
myEditText.setOnFocusChangeListener((view, hasFocus) -> {
if(hasFocus){
Log.e("TAG", "myEditext has focus")
}else{
Log.e("TAG", "myEditext has no focus")
}
});
In your activity or fragment implement OnFocusChangeListener.
edittextNeme= (EditText) findViewById(R.id.edittextNeme);
edittextNeme.setOnFocusChangeListener(this);
You will have to check which view changed focus by getting the view id with view.getId() and handle accordingly.
#Override
public void onFocusChange(View view, boolean hasfocus) {
switch(view.getId()){
case R.id.edittextNeme:
//Do something
break;
...etc
}
}
val currentFocusView = activity.currentFocus
if (currentFocusView is EditText){
currentFocusView.appendText("Has Focus!")
}
I have actually read several answers to this but they are so different than the simple way I am implementing click responses that I am wondering if there is a way to add something simple to what I am doing to create an onLongClick responas.
Basically, all my XML code is written with statements like this:
android:onClick="onSync"
Then my Java has:
public void onSync(View v) {
...
Toast toast3=Toast.makeText(this, "Sync was pressed",Toast.LENGTH_SHORT);
toast3.show();
}
What I would like to do is have a different function that is called when the button gets a long press. Right now, a long press causes the same action as a short press.
Specifically, I would like to know how to interface to a routine such as this:
public void onSyncLong(View v) {
...
Toast toast3=Toast.makeText(this, "Long Sync was pressed",Toast.LENGTH_SHORT);
toast3.show();
}
I would certainly appreciate any help on this problem. It would be great if the reply told me what to do in the XML and in the Jave. Thanks so much.
----------------------------UPDATE------------------------
Here is my onCreate code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.start_meters);
textLL = (TextView)findViewById(R.id.textLL);
textTimer = (TextView)findViewById(R.id.textTimer);
textTimeToLine = (TextView)findViewById(R.id.textTimeToLine);
Button button = (Button) findViewById(R.id.button_sync);
button.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
return true;
}
});
}
And here is the button XML segment
<Button
android:id="#+id/buttonSync"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Gun/Sync"
android:onClick="onSync"
android:textSize="#dimen/font_small"
android:background="#drawable/round_button"
android:padding="3sp"
android:longClickable="true"/>
------------Final Update----------------
Here is the working code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.start_meters);
textLL = (TextView)findViewById(R.id.textLL);
textTimer = (TextView)findViewById(R.id.textTimer);
textTimeToLine = (TextView)findViewById(R.id.textTimeToLine);
Button button = (Button) findViewById(R.id.buttonSync);
button.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
StartLine2.startTime = pTime + 1000*60*5;
return true;
}
});
}
You can't do this via XML. Instead, use:
Button button = (Button) findViewById(R.id.<your_id>);
button.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
return true;
}
});
Make sure this code comes after setContentView() has been called.
Also, make sure that the android:longClickable property is set to true.
In your XML, the ID is set to buttonSync, while in the Java code you're using button_sync. This is the reason for your NullPointerException, as you don't have a button called button_sync.
public class GameScoreFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
Log.v("TTT", "GameScoreFragment.OnCreateView()");
View viewScore = inflater.inflate(R.layout.gamescorelayout, container, false);
// set onLongClick listeners for both buttons
// when player long presses any of the two buttons, scores are reset
Button tempButton = (Button) viewScore.findViewById(R.id.id_button_pone_score);
tempButton.setOnLongClickListener( mLongListener );
tempButton = (Button) viewScore.findViewById(R.id.id_button_ptwo_score);
tempButton.setOnLongClickListener( mLongListener );
return viewScore;
}
// define a variable mLongListener to hold the listener code
// and then use mLongListener to set the listener
// if we don't define the variable, then we will have to write the listener code at two places (once for each button)
private View.OnLongClickListener mLongListener = new View.OnLongClickListener() {
#Override
public boolean onLongClick(View pView) {
//reset player scores
GameFragment tempGameFragment = (GameFragment) getFragmentManager().findFragmentById(R.id.id_gamefragment);
if (tempGameFragment != null)
tempGameFragment.resetPlayersScore(false);
return true;
}
};
}
I have this code:
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
button1.setBackgroundResource(R.drawable.detailpressed);
Chapter_sync.add(chapid);
}
What I am trying to do is toggle all the methods called in the following clicklistener.
Eg first time when I Click this button the setBackgroundResource(R.drawable.detailpressed) is called and on the next click same metod is called with different drawable.
Something like toggle button.
Someone good at this plz help?
you can take a variable
int i=0;
it will increase with every click.
if(i%2==0)
set one image
else
set another image
How about creating an array of the drawable's IDs and saving an index:
private final int[] myDrawables = {R.drawable.detailpressed, R.drawable.detailpressed1, ...};
//...
button1.setOnClickListener(new OnClickListener() {
int index = 0;
#Override
public void onClick(View v) {
button1.setBackgroundResource(myDrawables[index++ % myDrawables.length]);
Chapter_sync.add(chapid);
}
}
declare variable as
boolean isOddClicked = true;
And update your click listener as
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Do stuff here for chnaging background of button
if(isOddClicked) {
button1.setBackgroundResource(R.drawable.detailpressed);
isOddClicked = false;
} else {
button1.setBackgroundResource(R.drawable.detailpressed_SECOND_IMAGE);
isOddClicked = true;
}
//Do your task
Chapter_sync.add(chapid);
}
NOTE: If your requirement moves between two images then you can use toggle button and customize it. It will work for same as your requirement.
if xml as the following
<code>
<Button
android:id="#+id/btnListView"
android:layout_width="35dp"
android:layout_height="35dp"
android:background="#drawable/list_view"
android:onClick="switchToListView"
android:visibility="visible"
/>
<Button
android:id="#+id/btnGridView"
android:layout_width="35dp"
android:layout_height="35dp"
android:background="#drawable/grid_view"
android:onClick="switchToGridView"
android:visibility="gone"
/>
<code>
handling Code will be like
<code>
public void switchToListView(View view) {
(Button) findViewById(R.id.btnListView).setVisibility(View.GONE);
(Button) findViewById(R.id.btnGridView).setVisibility(View.VISIBLE);
}
public void switchToGridView(View view) {
(Button) findViewById(R.id.btnGridView).setVisibility(View.GONE);
(Button) findViewById(R.id.btnListView).setVisibility(View.VISIBLE);
}
</code>
I want to use the android select text functionality on OnClickListener rather than onlongclicklistener. Is there any way to do this? Can anybody help me regarding this? Thanks
with xml:
android:selectAllOnFocus="true"
with code (option1):
yourEditText.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//((EditText)v).selectAll();
((EditText)v).setSelection(startValue, stopValue);
}
});
with code (option2):
yourEditText.setOnFocusChangedListener(new OnFocusChangedListener(){
#Override
public void onFocusChange(View v, boolean hasFocus){
if (hasFocus){
//((EditText)v).selectAll();
((EditText)v).setSelection(startValue, stopValue);
}
}
});
This answer gives you several options if you want to select all the text.
If not then use an onclicklistener and call setSelection on your EditText.
EDIT:
theEditText.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
EditText editText = (EditText)view;
editText.setSelection(editText.getText().length()-1); // selects all the text
}
});
A totally different approach would be to try calling performLongClick from your EditText's onClick handler. This might let you use the default long click functionality, but call it from your onClick.
theEditText.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
EditText editText = (EditText)view;
editText.performLongClick();
}
});
This question already has answers here:
Why does my Android app crash with a NullPointerException when initializing a variable with findViewById(R.id.******) at the beginning of the class?
(9 answers)
Android setOnClickListener method - How does it work?
(5 answers)
Closed 1 year ago.
I'm trying to set and onclicklistener so that when I click within the edittext element it will clear its current contents. Is there something wrong here? When I compile this code I get a force quit and ActivityManager: Can't dispatch DDM chunk 4d505251: no handler defined error.
public class Project extends Activity implements OnClickListener {
/** Called when the activity is first created. */
EditText editText = (EditText)findViewById(R.id.editText1);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
editText.setOnClickListener(this);
setContentView(R.layout.main);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
editText.setText("");
}
}
Also you can use code below
editText.getText().clear();
First you need to call setContentView(R.layout.main) then all other initialization.
Please try below Code.
public class Trackfolio extends Activity implements OnClickListener {
/** Called when the activity is first created. */
public EditText editText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editText = (EditText) findViewById(R.id.editText1);
editText.setOnClickListener(this);
}
#Override
public void onClick(View v) {
editText.getText().clear(); //or you can use editText.setText("");
}
}
just use the android:hint attribute in your EditText. This text shows up when the box is empty and not focused, but disappears upon selecting the EditText box.
We can clear EditText data in two ways
First One setting EditText is empty like below line
editext.setText("");
Second one clearing EditText data like this
editText.getText().clear();
I suggest second way
Your code should be:
public class Project extends Activity implements OnClickListener {
/** Called when the activity is first created. */
EditText editText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editText = (EditText)findViewById(R.id.editText1);
editText.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v == editText) {
editText.setText("");
}
}
}
For Kotlin:
Create two extensions, one for EditText and one for TextView
EditText:
fun EditText.clear() { text.clear() }
TextView:
fun TextView.clear() { text = "" }
and use it like
myEditText.clear()
myTextView.clear()
public EditText editField;
public Button clear = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text_layout);
this. editField = (EditText)findViewById(R.id.userName);
this.clear = (Button) findViewById(R.id.clear_button);
this.editField.setOnClickListener(this);
this.clear.setOnClickListener(this);
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==R.id.clear_button){
//setText will remove all text that is written by someone
editField.setText("");
}
}
Very Simple to clear editText values.when u click button then only follow 1 line code.
Inside button or anywhere u want.Only use this
editText.setText("");
package com.example.sampleproject;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
public class SampleProject extends Activity {
EditText mSearchpeople;
Button mCancel , msearchclose;
ImageView mprofile, mContact, mcalender, mConnection, mGroup , mFollowup , msetting , mAddacard;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard);
mSearchpeople = (EditText)findViewById(R.id.editText1);
mCancel = (Button)findViewById(R.id.button2);
msearchclose = (Button)findViewById(R.id.button1);
mprofile = (ImageView)findViewById(R.id.imageView1);
mContact = (ImageView)findViewById(R.id.imageView2);
mcalender = (ImageView)findViewById(R.id.imageView3);
mConnection = (ImageView)findViewById(R.id.imageView4);
mGroup = (ImageView)findViewById(R.id.imageView5);
mFollowup = (ImageView)findViewById(R.id.imageView6);
msetting = (ImageView)findViewById(R.id.imageView7);
mAddacard = (ImageView)findViewById(R.id.imageView8);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
mCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mSearchpeople.clearFocus();
}
});
}
}
i don't know what mistakes i did while implementing the above solutions, bt they were unsuccessful for me
txtDeck.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
txtDeck.setText("");
}
});
This works for me,
//To clear When Clear Button is Clicked
firstName = (EditText) findViewById(R.id.firstName);
clear = (Button) findViewById(R.id.clearsearchSubmit);
clear.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.clearsearchSubmit);
firstName.setText("");
}
});
This will help to clear the wrong keywords that you have typed in so instead of pressing backspace again and again you can simply click the button to clear everything.It Worked For me. Hope It Helps
final EditText childItem = (EditText) convertView.findViewById(R.id.child_item);
childItem.setHint(cellData);
childItem.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
//Log.d("NNN", "Has focus " + hasFocus);
if (hasFocus) {
Toast.makeText(ctx.getApplicationContext(), "got the focus", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(ctx.getApplicationContext(),
"loss the focus", Toast.LENGTH_SHORT).show();
}
return;
});
by setting Empty string you can clear your edittext
editext.setText("");
If the use of EditText is not mandatory, you can implement this behavior easily with the new material components:
<com.google.android.material.textfield.TextInputLayout
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/hint_field"
app:endIconDrawable="#drawable/ic_close_black_24dp"
app:endIconMode="clear_text"
app:endIconTint="#color/black">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/hint_value"
android:maxLines="1"
android:text="#{itemModel.value}" />
</com.google.android.material.textfield.TextInputLayout>
You only have to specify the drawable you want for the button that will clear the text and the action that it will execute. To clear the text, you can use iconMode="clear_text", but also "password_toggle" is available.
In XML you can write like:
<EditText
android:id="#+id/txtsearch"
android:layout_width="250dp"
android:layout_height="match_parent"
android:layout_gravity="right"
android:layout_weight="1"
android:background="#drawable/roundlayoutbutton1"
android:ems="10"
android:gravity="center"
android:inputType="text"
android:textAllCaps="true"
android:text="search_xxxx"
android:textColor="#color/colorPrimaryDark"
android:visibility="visible" />
and in java class you may have below one :
EditText searchHost;
OnCreate() you write:
searchHost=findViewById(R.id.txtsearch);
searchHost.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(searchHost.getText().toString().equalsIgnoreCase("search_xxxx")){
searchHost.setText("");
Toast.makeText(getApplicationContext(),"Enter you text xxx...", Toast.LENGTH_LONG).show();
}
}
});
It works fine for me.
You can use the 'android:hint' attribute in your EditText also from code:
editText.setHint(CharSequence hint / int resid);
Then you don't need any onClickListener or similar. But consider that the hint value won't be passed. The editText will be stayed empty. In this case you can set your editText with your deflault value:
if(editText.getText().toString().equals("")) {
...use your default value instead of the editText... }
It's simple: declare the widget variables (editText, textView, button etc.) in class but initialize it in onCreate after setContentView.
The problem is when you try to access a widget of a layout first you have to declare the layout. Declaring the layout is setContentView.
And when you initialize the widget variable via findViewById you are accessing the id of the widget in the main layout in the setContentView.
I hope you get it!
I am not sure if your searching for this one
{
<EditText
.
.
android:hint="Please enter your name here">
}