Well im trying to get the text on each button, it displays the text correctly on each but when i try to print it, it shows the same text. The text of optionD
private void displayQuestion() {
final ArrayList<String> options = new ArrayList<>();
for (int i = 0; i < questions.size(); i++){
Questions diaplayQuestion = questions.get(i);
question.setText(diaplayQuestion.getQuestion());
options.add(0, diaplayQuestion.getOptionA());
options.add(1, diaplayQuestion.getOptionB());
options.add(2, diaplayQuestion.getOptionC());
options.add(3, diaplayQuestion.getOptionD());
correctOption = diaplayQuestion.getCorrectOption();
}
for (int i = 0; i < options.size(); i++) {
btn = new Button(GameplayActivity.this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(10, 10, 10, 0);
btn.setLayoutParams(params);
btn.setText(options.get(i));
btn.setId(i);
linearLayout.addView(btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
System.out.println(view.getId());
}
});
}
}
If you want to store some information inside View use tags. From official docs:
Unlike IDs, tags are not used to identify views. Tags are essentially an extra piece of information that can be associated with a view. They are most often used as a convenience to store data related to views in the views themselves rather than by putting them in a separate structure.
So in your case it'll be like this:
btn = new Button(GameplayActivity.this);
...
btn.setTag(options.get(i)); // I assume that value is String
...
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
System.out.println((String) view.getTag());
}
});
Related
Android: I have created dynamic buttons based on my arraylist size,Lets consider 10 buttons. When a button is clicked, the color of the button will change to grey. When another one is clicked, the color of the previous button should be reset to the default color.
boolean iscolor = true;
final LinearLayout linearLayout = view.findViewById(R.id.total_count);
final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
for (int j =1;j<=datalist.size()/2;j++) {
final Button btn = new Button(getContext());
final int id_ = j;
btn.setText("" + j);
btn.setTextColor(Color.WHITE);
btn.setMaxWidth(5);
btn.setId(id_);
btn.setPadding(8, 8, 8, 8);
btn.setBackgroundColor(getContext().getResources().getColor(R.color.DarkBlue));
linearLayout.addView(btn, params);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!iscolor ) {
btn.setBackgroundColor(getResources().getColor(R.color.DarkBlue));
iscolor =true;
}
else
{
btn.setBackgroundColor(getResources().getColor(R.color.gray));
iscolor = false;
}
}});
How to restore the color of the previous clicked Button in Android.
Try this :
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* you need to have already stored buttons in a data structure, something like : List<Button> btns; */
for(Button b : btns){
if(b.getId() == v.getId(){ b.setBackgroundColor(getResources().getColor(R.color.gray)); } else{ b.setBackgroundColor(getResources().getColor(R.color.yourdefaultcolor)); } //no need for isColor variable
}});
linearLayout.addView(btn, params);
I have created a set of TextViews programmatically using a for loop. This what i have tried.
for(int i=1; i<5; i++){
valueTV = new TextView(AddMyVehicle.this);
linearLayout.addView(valueTV);
vehicleModelReturned = myVehicleData.getString("VehicleModel"+x, "");
valueTV.setText(vehicleModelReturned);
valueTV.setGravity(Gravity.CENTER_HORIZONTAL);
valueTV.setTextSize(TypedValue.COMPLEX_UNIT_SP,22);
valueTV.setTextColor(Color.parseColor("#333333"));
i++;
}
this.valueTV.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
valueTV.setText("Hello");
}
});
I need to change the text of clicked TextView to "Hello". How can i achieve this?
You have to add a listener to all your TextView created.
And be careful, you incremented i twice : one in the first line of the for and another one in the end of the for.
for (int i = 1; i < 5; i++)
{
final TextView valueTV = new TextView(AddMyVehicle.this);
linearLayout.addView(valueTV);
vehicleModelReturned = myVehicleData.getString("VehicleModel" + x, "");
valueTV.setText(vehicleModelReturned);
valueTV.setGravity(Gravity.CENTER_HORIZONTAL);
valueTV.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22);
valueTV.setTextColor(Color.parseColor("#333333"));
valueTV.setId("test");
valueTV.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
TextView tv = (TextView) v;
tv.setText("Hello");
}
});
}
First, set the OnClickListener to all the TextViews you create, not just the last one. That is, move the setOnClickListener() inside the for loop.
Second, in onClick(), change the text of the clicked view and not again the last one you created. The View v param is the view that was clicked. You can cast it to TextView.
i have added some button in a layout:
LinearLayout row = (LinearLayout)findViewById(R.id.KeysList);
keys=db.getKeys(console);
my_button=new Button[keys.size()];
for (bt=0;bt<keys.size();bt++){
my_button[bt]=new Button(this);
my_button[bt].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.FILL_PARENT));
my_button[bt].setText(keys.get(bt));
my_button[bt].setId(bt);
row.addView(my_button[bt]);
my_button[bt].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (my_button[bt].getId() == ((Button) v).getId()){
Toast.makeText(getBaseContext(), keys.get(bt), 0).show();
}
}
});
}
I want to know which button is clicked and how to get text of the clicked button?And I think using bt here dose not seem to work!
This code is running. I hope it help you :)
final ArrayList<String> Keys = new ArrayList<String>();
for(int i = 0; i < 10; i ++){
Keys.add("Keys is : " + String.valueOf(i));
}
LinearLayout Row = (LinearLayout)findViewById(R.id.KeysList);
final Button[] my_button = new Button[Keys.size()];
for (int bt = 0; bt < Keys.size(); bt ++){
final int Index = bt;
my_button[Index] = new Button(this);
my_button[Index].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
my_button[Index].setText(Keys.get(Index));
my_button[Index].setId(Index);
my_button[bt].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (my_button[Index].getId() == ((Button) v).getId()){
Toast.makeText(getBaseContext(), Keys.get(Index), 0).show();
}
}
});
Row.addView(my_button[Index]);
}
ExampleProject id : Your project
You should probably use View#setTag to set some arbitrary data you'd like associate with the Button. Then you can just instantiate only one OnClickListener that then uses getTag and acts on that data in whatever way you need.
Another way is to have your Activity listen to all button clicks and then you just filter respective to the ID. You should not get the text of the button and use that at all. You should use your own type of identifier, ideally the idea should be enough. Or perhaps you use setTag as #qberticus described.
Consider This example :
public class MainActivity extends Activity implements View.OnClickListener
{
LinearLayout linearLayout;
Button [] button;
View.OnClickListener listener;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout=(LinearLayout)findViewById(R.id.parent_lay);
String[] array={"U123","U124","U125"};
int length=array.length;
System.out.println("11111111111111111111111111");
button=new Button[length];
for(int i=0;i<length;i++)
{
button[i]=new Button(getApplicationContext());
button[i].setId(i);
button[i].setText("User" + i);
button[i].setOnClickListener(this);
linearLayout.addView(button[i]);
}
}
#Override
public void onClick(View view)
{
view.getId();
Button button=(Button)findViewById(view.getId());
button.setText("Changed");
}
}
This works fine :)
Say I have buttons that are created dynamically:
for(int j = 0; j < spirits.length;
j++){
Button imgBtn = new Button(v.getContext());
imgBtn.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
imgBtn.setMinimumWidth(100);
imgBtn.setMinimumHeight(100);
imgBtn.setId(j+1);
imgBtn.setTag(spirits[j]);
imgBtn.setText(spirits[j]);
imgBtn.setOnClickListener(new SpiritsClickListener());
cabinet_layout.addView(imgBtn);
}
I want to change the text of the button every time it's pressed (On - Off)
How can I reference the buttons within the OnClickListener class?
in your onClickListener, you have a function called onClick(View v){} where v is the View that was clicked. You may use v to get details about the button, including its ID. You can also take this view, and if you know it is a button, cast it to a button.
Button clicked = (Button)v;
You can then use it in your javacode just as you would normally use a button.
Why don't you just call new OnClickListener() inside that loop like this
for(int j = 0; j < spirits.length;j++){
Button imgBtn = new Button(v.getContext());
imgBtn.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
imgBtn.setMinimumWidth(100);
imgBtn.setMinimumHeight(100);
imgBtn.setId(j+1);
imgBtn.setTag(spirits[j]);
imgBtn.setText(spirits[j]);
imgBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//do what you need to do here
}
});
cabinet_layout.addView(imgBtn);
}
Create an OnClickListener for dynamically created buttons as:
// Create Listener for Button
private OnClickListener SpiritsClickListener = new OnClickListener()
{
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
Button btn = (Button) view;
String btnText = btn.getText();
if(btnText.equalsIgnoreCase("On")){
btn.setText("Off");
}else{
btn.setText("On");
}
}
};
add this Listener to dynamically created buttons as:
imgBtn.setOnClickListener(SpiritsClickListener);
A table is being created such that:
TableLayout layout = new TableLayout(this);
layout.setLayoutParams(new TableLayout.LayoutParams(4,5));
layout.setPadding(1, 1, 1, 1);
for(int i=0; i<7; i++) {
TableRow tr = new TableRow(this);
for(int j=0; j<6; j++) {
Button b = new Button(this);
b.setText("0");
b.setOnClickListener(buttonListener);
tr.addView(b);
}
layout.addView(tr);
}
super.setContentView(layout);
The OnClickListener buttonListener is:
View.OnClickListener buttonListener = new View.OnClickListener() {
public void onClick(View v) {
Button thisButton = (Button) findViewById(((Button)v).getId());
//thisButton.setText(Integer.toString(Integer.parseInt((String) thisButton.getText()) + 1));
thisButton.getText();
}
};
The call to thisButton.getText() throws a NullPointerException, and I'm not sure why. Can anyone help me out?
TableLayout layout = new TableLayout(this);
layout.setLayoutParams(new TableLayout.LayoutParams(4,5));
layout.setPadding(1, 1, 1, 1);
for(int i=0; i<7; i++) {
TableRow tr = new TableRow(this);
for(int j=0; j<6; j++) {
Button b = new Button(this);
b.setText("0");
b.setOnClickListener(buttonListener);
tr.addView(b);
}
layout.addView(tr);
}
setContentView(layout);
}
View.OnClickListener buttonListener = new View.OnClickListener() {
public void onClick(View v) {
Button btn1 = (Button)v;
//thisButton.setText(Integer.toString(Integer.parseInt((String) thisButton.getText()) + 1));
String name = btn1.getText().toString();
}
};
I have tested this will work.
When you create view dynamically you don't to assgin an id to it.
you work using the object of the view.
I hope it makes sense to all the people who are curious to set id for dynamic buttons.
One problem in your code.
Have not set id of Button
b.setText("0");
b.setOnClickListener(buttonListener);
b.setId(i);
Assumption:
I can't see anything regarding setting id to button
The below line may causing exception:
Button thisButton = (Button) findViewById(((Button)v).getId());
Why are you doing? Instead you are already passing a view in click action: View v
So you can do straight way like:
String strText = ((Button) v).getText();
It mean your thisButton is probably null, because the statement before that was not successful.
Button thisButton = (Button) findViewById(((Button)v).getId());
does not look right. Usually the paramenter inside findViewById() should be a resource id.
such as
Button thisButton = (Button) findViewById(R.id.button);
R.id.button is defined by your layout xml.
You may simply get the text from the passed view, instead of recreating a button.
public void onClick(View v) {
if(v instanceof Button)
String text = ((Button) v).getText();
}