I have dynamically created Textviews in my application. I want to give On click event to this textviews.. When I click on the textview, I need to get the id of the textview..
You try following code.
TextView text = new TextView(this);
text.setText("text here");
ll.addView(text);
text.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "ID : "+arg0.getId(), Toast.LENGTH_SHORT).show();
}
});
in that "ll" is Layout which add textview and after adding put clickListener() for click event.
hope this is useful for you.
Have a look at setOnClickListener and getId.
TextView textView = new TextView(this);
// Set up your text view
textView.setId(1); // Any number is ok
textView.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
int id = v.getId(); // This is the id you want
// Do whatever you want here
}
});
If you are creating TextViews dynamically than just implement OnClickListener:
import android.view.View;
import android.view.View.OnClickListener;
public class MyClickListener implements OnClickListener {
#Override
public void onClick(View v) {
int vId = v.getId();
}
}
and set it to dynamically created view like this:
private TextView createTextView(int vId) {
TextView textView = new TextView(this);
textView.setId(vId);
textView.setOnClickListener(myClickListener);
return textView;
}
P.S.: Don't forget to create & initilialize myClickListener in your Activity.
For my own practice I am a creating an array of 3 buttons in the instance field and i would like all of them to have setOnClickListeners,which allow each button to change the BackGround Color of a text View.Can any person please guide me towards the right direction.Here is my code:
public class MainActivity extends Activity {
Button b = {(Button)findViewById(R.id.button1),
(Button)findViewById(R.id.button2),
(Button)findViewById(R.id.button3),};
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView1);
for(int i=0; i < b.length;i++){
b[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(butt[0].isPressed()){
tv.setBackgroundColor(Color.BLACK);
}
if(b[1].isPressed()){
tv.setBackgroundColor(Color.BLUE);
}
if(b[2].isPressed()){
tv.setBackgroundColor(Color.RED);
}
}
});
}
}
}
You aren't declaring an Array for your Buttons. I'm not sure what this would do or if it would even compile but I wouldn't think so
Button b = {(Button)findViewById(R.id.button1),
(Button)findViewById(R.id.button2),
(Button)findViewById(R.id.button3),};
Change it to
Button[] b = {(Button)findViewById(R.id.button1),
(Button)findViewById(R.id.button2),
(Button)findViewById(R.id.button3),};
Also, this code has to go after setcontentView() or you will get a NPE since your Buttons exist in your layout and your layout doesn't exist until you inflate it by calling setContentView().
You can declare your Array before onCreate() but you can't initialize them until you inflate your layout
So you can do something like this
public class MainActivity extends Activity {
Button[] b = new Button[3]; //initialize as an array
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = {(Button)findViewById(R.id.button1),
(Button)findViewById(R.id.button2),
(Button)findViewById(R.id.button3),}; //add buttons AFTER calling setContentView()
...
Edit Since #pragnani deleted his answer I will edit with a bit of it that is a good idea
You can simplify your logic by choosing which Button was clicked with a switch by doing something like below in your for loop
b[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) { / v is the button that was clicked
switch (v.getId()) //so we get its id here
{
case (R.id.button1):
tv.setBackgroundColor(Color.BLACK);
break;
case (R.id.button2):
tv.setBackgroundColor(Color.BLUE);
break;
case (R.id.button3):
tv.setBackgroundColor(Color.RED);
break;
}
In my App I have a line showing an (ImageButton)icon and a (textView)title of an audio file to play and I use the setOnClickListener for an ImageButton to initiate a process that plays the file. I would also like to use the (textView)title as a clickable item to begin the same process.
I could simply duplicate all of the functionality in both setOnClickListeners but that does not seem to be the most efficient way to do it.
Now I am new so is there such a thing as
ImageButton.setOnClickListener() || textView.setOnClickListener() {
.
.
.
}
Basically if the ImageButton is clicked or the textView is clicked do this procedure.
I know the above syntax is not correct but it gives you an idea of what I want to do
Have the class that has both these elements ImageButton and textView implement the OnClickListener. OnClickListener is an interface that has the method onClick(View v) which will have the click implementation for both these elements. Then you can use imageButton.setOnClickListener(this) and textView.setOnClickListener(this).
Example Code:
public MyClass extends Activity implements OnClickListener {
ImageButton imageButton;
TextView textView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
imageButton = (ImageButton) findViewById(R.id.btn);
textView = (TextView) findViewById(R.id.txt);
imageButton.setOnClickListener(this);
textView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int viewId = v.getId() ;
if(viewId == R.id.btn || viewId == R.id.txt){
//common implementation of click event
}
}
}
Hope this explanation helps.
ImageButton iv=(ImageButton)findViewById(R.id.imagebutton1);
TextView tv=(TextView)findViewById(R.id.textview1);
iv.setOnClickListener(OnClick);
tv.setOnClickListener(OnClick);
add this in OnCreate() method and after that add this method as shown below
private OnClickListener OnClick=new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.imagebutton1:{
// do here code what u want on imagebutton click
break;}
case R.id.textview1:{
// do here code what u want on textview click
break;}
}
}
}
};
Put both the imagebutton and textview in a layout and give it an ID. Then implement the onClickListener for the layout, by this way you need to write the code only once.
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">
}
This is going to be a bit lame question. I have the following code:
..............
public void onCreate (Bundle bundle)
{
super.onCreate(bundle);
this.setContentView(R.layout.main2);
Button bnt = (Button) this.findViewById(R.id.browser);
bnt.setOnClickListener(new ButtonListener());
}
..............
class ButtonListener implements android.view.View.OnClickListener
{
public void onClick(View v)
{
// I have a TextView in my xml layout file.
// I'd like to get it and change my text when I click this button.
// But I can't get it (the TextView) unless I make it as a value of a static member of this class and pass it to the constructor.
//I believe I am missing a big point here, so i'd be very thankful if you could explain how this is meant to be done ?
}
}
Any help is appreciated.
You could try this:
class ButtonListener implements android.view.View.OnClickListener {
public void onClick(View v) {
View parent = (View)v.getParent();
if (parent != null) {
TextView txtView = parent.findViewById(R.id.mytextview);
txtView.setText(...);
}
}
}
the usage depends on your layout. Its possible, that the parent of your button is not the parent of your textview so be careful...
class ButtonListener implements android.view.View.OnClickListener {
public void onClick(View v) {
View p = (View) view.getRootView();
if (p != null) {
TextView txtView = (TextView) p.findViewById(R.id.mytextview);
txtView.setText(...);
}
}
}
I need to set visible an element from the same parent so I used this code :) and it worked
EDIT
I dont think it will be possible. The view V only has the buttons view in it....
You will know if you typecast the same
class ButtonListener implements android.view.View.OnClickListener
{
public void onClick(View v)
{
Button vg=(Button)v;
Log.e("", "views are "+vg.getText());
//However u can set the test here for ue textview
txt.setText("change text");
}
}
I did not understand your question properly. But if you just want to get the text out from ur TextView you can try like this
TextView txt;
public void onCreate (Bundle bundle)
{
super.onCreate(bundle);
this.setContentView(R.layout.main2);
Button bnt = (Button) this.findViewById(R.id.browser);
txt=(TextView)this.findViewById(R.id.urtextview);
bnt.setOnClickListener(new ButtonListener());
}
..............
class ButtonListener implements android.view.View.OnClickListener
{
public void onClick(View v)
{
// I have a TextView in my xml layout file.
// I'd like to get it and change my text when I click this button.
// But I can't get it (the TextView) unless I make it as a value of a static member of this class and pass it to the constructor.
//I believe I am missing a big point here, so i'd be very thankful if you could explain how this is meant to be done ?
//I think this should get u the string...
System.out.println("text is "+txt.getText().toString());
}
}