android dynamic button with setOnClickListener - java

I try to create dynamic buttons. When a button is clicked, the color of the button will change to red. When another one is clicked, the color of the previous button should be reset to the default color.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout linear;
linear = (LinearLayout) findViewById(R.id.ly);
for (i = 1; i < 4; i++) {
final Button btn = new Button(this);
btn.setId(1000 + i);
btn.setBackgroundColor(Color.BLUE);
btn.setMinimumHeight(150);
btn.setMinimumWidth(150);
linear.addView(btn);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
btn.setBackgroundColor(Color.RED);
}
});
}
How can I get the id of the non clicked button?

You can try this:
ArrayList<Button> mButtonList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout linear;
linear = (LinearLayout) findViewById(R.id.ly);
for (int i = 1; i < 4; i++) {
final Button btn = new Button(this);
btn.setId(1000 + i);
btn.setBackgroundColor(Color.BLUE);
btn.setMinimumHeight(150);
btn.setMinimumWidth(150);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
for (Button button : mButtonList) {
if (button.getId() == view.getId()) {
button.setBackgroundColor(Color.RED);
} else {
button.setBackgroundColor(Color.BLUE);
}
}
}
});
linear.addView(btn);
mButtonList.add(btn);
}
}

Add implements onClickListener to Your Activity and set this listener to you button in for loop like
valueB.setOnClickListener(this);
And Override the onClick method where you get button id
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "" + v.getId(), 800).show();
}
Once you get button id you can change text color

Related

How to delete individual elements from textview on Android studio

I am doing this project, can anyone help me to delete individual elements from the text view?enter image description here
here's i implemented the 'button' to insert and 'button2' to delete, and here's the code down bellow
public class MainActivity extends Activity {
private EditText editText;
private Button button;
private TextView textView;
private static final String TAG = "MainActivity";
// To hold all data in different mode : Portrait and landscape
private final String text_context = "TX";
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate: in");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText)findViewById(R.id.editText);
button = (Button)findViewById(R.id.button);
textView = (TextView)findViewById((R.id.textView));
textView.setText(""); // make it no text at runtime, but text at view
textView.setMovementMethod(new ScrollingMovementMethod()); // make it scrolling
editText.setText("");
final View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
String result = editText.getText().toString();
result += "\n";
textView.append(result);
editText.setText(""); // text on EDITTEXT will disappear as soon as we click the button
}
};
final View.OnClickListener onClickListener1 = new View.OnClickListener() {
#Override
public void onClick(View view) {
}
};
if(editText != null)
button.setOnClickListener(onClickListener);
Log.d(TAG, "onCreate:out");
}
}
Please help me TO IMPLEMENT DELETE ACTION VIA BUTTON2....
Right now your onclick listeners are generically listening for clicks on any view.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Handle button events
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Handle button2 events
}
});
Or better yet implement View.OnClickListener() on your activity
Use regex
String input = editText.getText().toString();
String regex = "\\b" + input + "\\b";
String tvText = textView.getText().toString();
tvText = tvText.replaceAll(regex, "");
textView.setText(tvText);
Put this code in
final View.OnClickListener onClickListener1 = new View.OnClickListener() {
#Override
public void onClick(View view) {
//code goes here
}
};
if(editText != null)
// add this onclick to your button2
button2.setOnClickListener(onClickListener1);
Log.d(TAG, "onCreate:out");
}

Adding onClick Listener on dynamically created elements not working

I am creating dynamic textview on runtime. on adding onClick() Listener. it works only on the last textview created on runtime and not on every textview created.
This is my code:-
#Override
public void onComplete(#NonNull Task<Object> task) {
if (task.isComplete()) {
ArrayList<Document> tagLocat = (ArrayList<Document>) task.getResult();
tv=new TextView[tagLocat.size()];
for (i = 0; i < tagLocat.size(); i++) {
Document doc = tagLocat.get(i);
TextView tv1 = new TextView(MainActivity.this);
Log.i("Document", "" + doc);
notification = doc.getString("notification");
Log.i("Double", "" + notification);
LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lparams.setMargins(10,10,10,10);
tv1.setLayoutParams(lparams);
tv1.setTag(i);
tv1.setId(i);
tv1.setTextSize(30);
tv1.setPadding(50, 0 ,0,0);
tv1.setText(notification);
tv[i] = tv1;
linearLayout.addView(tv[i]);
tv[i].setBackgroundColor(Color.GRAY);
tv[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tv[i].setBackgroundColor(Color.LTGRAY);
}
});
}
} else {
Log.i("Exception",task.getException().toString());
}
}
You have to add your textview in array after set onclicklistener
like
tv1.setLayoutParams(lparams);
tv1.setTag(i);
tv1.setId(i);
tv1.setTextSize(30);
tv1.setPadding(50, 0 ,0,0);
tv1.setText(notification);
tv1.setBackgroundColor(Color.GRAY);
tv1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.setBackgroundColor(Color.LTGRAY);
}
});
tv[i] = tv1;
linearLayout.addView(tv[i]);
Set onClickListener before adding view .
Solution:-
for (int i = 0; i < tagLocat.size(); i++) {
// Do stuff here
tv[i].setBackgroundColor(Color.GRAY);
tv[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.setBackgroundColor(Color.LTGRAY);
}
});
tv[i] = tv1;
linearLayout.addView(tv[i]);
}
Make sure this will not toggle the color onClick().If you want such behaviour you need to maintain the state of TextView.

i want to create a counter with a text view

i want to create a counter with a text view and want for every 15 click , to change the text in the text view and that is what i have wrote to create the counter ........ i have two text views .... one for the no. of clicks and the another for the text i want to show ,,,,,,,,,,, so i want to use "if" to set the counter to 0 (the counter is tvx) and to change the text (tvx2) to "click 15 more"
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tips_2);
btn = (Button) findViewById(R.id.bt);
txv = (TextView) findViewById(R.id.tx);
txv2 = (TextView) findViewById(R.id.tx2);
btn.setOnClickListener(new View.OnClickListener()
{
public int mCounter;
public Integer tx;
#Override
public void onClick(View v) {
mCounter++;
txv.setText(Integer.toString(mCounter));
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tips_2);
btn = (Button) findViewById(R.id.bt);
txv = (TextView) findViewById(R.id.tx);
txv2 = (TextView) findViewById(R.id.tx2);
public int mCounter=0;
public Integer tx =15;
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCounter++;
if(mCounter==tx){
txv.setText(Integer.toString(mCounter));
//reset the counter after 15 click
mCounter=0
}
}
}
);
}
}
you can this way, use the ValueAnimator
public void animateText(Integer startValue, Integer endValue) {
setStartValue(startValue);
setEndValue(endValue);
ValueAnimator animator = ValueAnimator.ofInt(startValue, endValue);
animator.setInterpolator(getInterpolator());
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
public void onAnimationUpdate(ValueAnimator animation) {
String cleanString = animation.getAnimatedValue().toString().replaceAll("[,]", "");
BigDecimal parsed = new BigDecimal(cleanString);
String formatted = NumberFormat.getNumberInstance(Locale.US).format(parsed);
tv.setText(formatted);
}
});
animator.setEvaluator(new TypeEvaluator<Integer>() {
public Integer evaluate(float fraction, Integer startValue, Integer endValue) {
return Math.round(startValue + (endValue - startValue) * fraction);
}
});
animator.setDuration(getDuration());
animator.start();
}
Hello Try this if it may help
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tips_2);
btn = (Button) findViewById(R.id.bt);
txv = (TextView) findViewById(R.id.tx);
txv2 = (TextView) findViewById(R.id.tx2);
btn.setOnClickListener(new View.OnClickListener() {
public int mCounter=0;
//initialize mCounter with 0
public Integer tx;
#Override
public void onClick(View v) {
if(mCounter==15){
//check if mCounter equals 15
txv2.setText(Integer.toString("text to display after 15 click"));
//reset mCounter for another iteration
mCounter=0;
}
mCounter++;
//increment the mCounter
txv.setText(Integer.toString(mCounter));
}
});
}
I'm not really understand what do you want, but if you want to increase the counter every 15 click, just add if conditional in your code like this:
btn.setOnClickListener(new View.OnClickListener() {
public int mCounter;
public Integer tx;
#Override
public void onClick(View v) {
mCounter++;
if(mCounter == 15){
tx++;
txv.setText(String.valueOf(tx));
}
}
}
);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tips_2);
btn = (Button) findViewById(R.id.bt);
txv = (TextView) findViewById(R.id.tx);
txv2 = (TextView) findViewById(R.id.tx2);
btn.setOnClickListener(new View.OnClickListener() {
public int mCounter;
public Integer tx;
public int mCounter2;
#Override
public void onClick(View v) {
mCounter++;
mCounter2++;
txv.setText(""+mCounter);
if(mCounter2==15){
txv2.setText(""+mCounter2);
mCounter2=0;
}
}
}
);
}
I hope and you serve this
public class MainActivity extends AppCompatActivity {
private Button btn;
private TextView txv,txv2;
private int contador = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.bt);
txv = (TextView) findViewById(R.id.tx);
txv2 = (TextView) findViewById(R.id.tx2);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
++contador;
if(contador <= 15){
txv.setText(String.valueOf(contador));
}else{
txv2.setText("your text");
}
}
});
}
}

every button click to change text view

i coded this lines to change textview1 Continuous when user clicked button but it sucks at value 1 in output why :\
public class dobeyti extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dobeyti);
final TextView tView;
Button mButton;
tView = (TextView)findViewById(R.id.textView1);
mButton = (Button)findViewById(R.id.button);
assert mButton != null;
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int num = 0;
num++;
tView.setText(Integer.toString(num));
}
});
}
}
Becuase you defined the num value inside the onclick method so it will be reassigned to 0 every time.
Just put int num=0 outside the method like below:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dobeyti);
final TextView tView;
Button mButton;
tView = (TextView)findViewById(R.id.textView1);
mButton = (Button)findViewById(R.id.button);
assert mButton != null;
mButton.setOnClickListener(new View.OnClickListener() {
int num = 0;
#Override
public void onClick(View v) {
num++;
tView.setText(Integer.toString(num));
}
});
}
}
Move int num = 0; outside OnClickListener. Every time you click button value on variable num is set to 0 -> increased to 1 and set as text, that is why it stuck at 1.
int num = 0;
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
num++;
tView.setText(Integer.toString(num));
}
});
}
}

value of final int to int

I am currently fooling around with the android SDK (eclipse) and i am trying to make a simple button-based TicTacToe game.
I made an array where i save the Buttons and i am trying to make the ClickEvents dynamically:
Here is the Code (Which works so far):
public class MainActivity extends Activity
{
final Button[] buttons = new Button[9];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttons[0] = (Button) findViewById(R.id.button1);
buttons[1] = (Button) findViewById(R.id.button2);
buttons[2] = (Button) findViewById(R.id.button3);
buttons[3] = (Button) findViewById(R.id.button4);
buttons[4] = (Button) findViewById(R.id.button5);
buttons[5] = (Button) findViewById(R.id.button6);
buttons[6] = (Button) findViewById(R.id.button7);
buttons[7] = (Button) findViewById(R.id.button8);
buttons[8] = (Button) findViewById(R.id.button9);
for(int i = 0;i < 9;i++)
{
buttons[i].setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
//
}
});
}
}
}
The problem comes when i try to reference to a button in the onClick-Method using 'i'.
For example:
#Override
public void onClick(View arg0)
{
//buttons[0].setText("X"); works by the way
buttons[i].setText("X");
}
Eclipse tells me: "Change modifier of 'i' to final"
Well but if 'i' would be final, i wouldn't be able to increase 'i' in the loop.
So i tried this:
#Override
public void onClick(View arg0)
{
final int position = i;
buttons[position].setText("X");
}
Which ends up resulting with the same Error "Change modifier of 'i' to final"
So my Question is: How can i make this work?
I have tried google but i wasn't able to find anything and this really is the first time i ever encountered this problem .
Hope you guys can help me out!
EDIT:
Well the solution was simple, here is the now working code:
for(int i = 0;i < 9;i++)
{
final int position = i;
buttons[i].setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
buttons[position].setText("X");
}
});
}
You can do something like this:
for(int i = 0;i < 9;i++)
{
final int position = i;
buttons[i].setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
buttons[position].setText("X");
}
});
}
Create another final int var in your loop set it the same value as i and reference this var from you listeners.
for(int i = 0;i < 9;i++)
{
final int index = i;
buttons[i].setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
buttons[index].setText("X");
}
});
}
Have a separate class which implements View.OnClickListener and have a constructor to accept the index value

Categories