Click Event On Dynamically Added TextViews in Android - android

I am trying to add 20 textviews and assign a onclick to dynamically added textviews. Problem is whenever i try to click any of the dynamic textiview. It always fires up click event of last added textview.
Here is my code:
EditText s;
EditText t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout containerLayout = (RelativeLayout) findViewById(R.id.container);
for (int i = 0; i < 20; i++) {
TextView dynaText = new TextView(this);
dynaText.setText("Some text " + i);
dynaText.setTextSize(30);
dynaText.setTag("" + i);
dynaText.setOnClickListener(btnClickListener);
// Set the location of your textView.
dynaText.setPadding(0, (i * 30), 0, 0);
containerLayout.addView(dynaText);
}
}
OnClickListener btnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
RelativeLayout ll = (RelativeLayout) v.getParent();
TextView tv = (TextView) ll.getChildAt(2);
// Integer pos = (Integer) tv.getTag();
Toast.makeText(v.getContext(), "Toast " + v.getTag(),
Toast.LENGTH_SHORT).show();
}
};
}

1) you should make your TextViews Clickable first :
for (int i = 0; i < 20; i++) {
TextView dynaText = new TextView(this);
dynaText.setText("Some text " + i);
dynaText.setTextSize(30);
dynaText.setTag("" + i);
dynaText.setClickable(true);//make your TextView Clickable
dynaText.setOnClickListener(btnClickListener);
// Set the location of your textView.
dynaText.setPadding(0, (i * 30), 0, 0);
containerLayout.addView(dynaText);
}
2) modify your onClickListener :
OnClickListener btnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("btnClickListener", ""-----TextView Clicked : "+v.getTag());
Toast.makeText(YourActivity.this, "TextView Clicked : "+v.getTag(),
Toast.LENGTH_SHORT).show();
}
};
EDIT : you are adding your TextViews one over one . that's why the click event fires on the last one added.
try to use a LinearLayout with android:orientation="vertical" , or try to add each new TextView bellow the previous one :
for (int i = 0; i < 20; i++) {
TextView dynaText = new TextView(this);
dynaText.setText("Some text " + i);
dynaText.setId(i+1);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
if(i!=0)
params.addRule(RelativeLayout.BELOW, i);
dynaText.setLayoutParams(params);
dynaText.setTextSize(30);
dynaText.setTag("" + i);
dynaText.setOnClickListener(btnClickListener);
containerLayout.addView(dynaText);
}

Try this:
OnClickListener btnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Toast " + v.getTag(),
Toast.LENGTH_SHORT).show();
}
};
Update:
The reason why you are clicking the last TextView is because it is just so big.. You are increasing the padding with each loop and when you click somewhere, it will always hit the last View because it is overlaying the others. Try a LinearLayout and remove the padding like so:
public class MainActivity extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout containerLayout = (LinearLayout) findViewById(R.id.container);
for (int i = 0; i < 20; i++) {
TextView dynaText = new TextView(this);
dynaText.setText("Some text " + i);
dynaText.setTextSize(30);
dynaText.setTag("" + i);
dynaText.setOnClickListener(this);
containerLayout.addView(dynaText);
}
}
public void onClick(View v) {
// do stuff
}
}
But having your problem solved.. I think a ListView would suit your purpose :)

Do in the following way to get the clicked data
Declare a variable
int sCount = 0;
for (int i = 0; i < 20; i++) {
TextView dynaText = new TextView(this);
dynaText.setId(1000+sCount);
dynaText.setText("Some text " + i);
dynaText.setTextSize(30);
dynaText.setTag("" + i);
dynaText.setOnClickListener(btnClickListener);
// Set the location of your textView.
dynaText.setPadding(0, (i * 30), 0, 0);
containerLayout.addView(dynaText);
}
OnClickListener btnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
RelativeLayout ll = (RelativeLayout) v.getParent();
TextView tv = (TextView) ll.getChildAt(2);
tv.addFocusables(null, v.getId(), 0);
Toast.makeText(v.getContext(), "Toast " + tv.getText(),
Toast.LENGTH_SHORT).show();
}
};
This works fine for you.

You can try to use anonymous instances for OnClickListener and create different instance of listener for each view. Something like this:
dynaText.setPadding(0, (i * 30), 0, 0);
dynaText.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((TextView) v).getText();
}
});
containerLayout.addView(dynaText);

Related

How can get dynamic button text from another dynamic button OnClickListener event

I want get second dynamic button text from another dynamic button OnClickListener event:
Here is define some dynamic buutons:
LinearLayout lv=(LinearLayout)findViewById(R.id.lv);
for (int k = 1; k <= str[0].length(); k++) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(100, 100);
btnTopEn = new Button(this);
btnTopEn.setId(k);
final int id_ = btnTopEn.getId();
btnTopEn.setText(" ");
lv.addView(btnTopEn, params);
btnTopEn = ((Button) findViewById(id_));
final Button finalBtnT = btnTopEn;
btnTopEn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
finalBtnT.setText("");
}
});
}
Now I want text of second button from OnClickListener Event:
TableLayout layout = (TableLayout)findViewById(R.id.TableL);
String stt="RZCEADHPTAUJTSFR";
int l=0;
for (int f=0; f<=1; f++) {
TableRow tr = new TableRow(this);
for (int c=0; c<=7; c++) {
btnCEn = new Button (this);
String ss=(String.valueOf(stt.charAt(l)));
btnCEn.setText(ss);;
final Button finalBtnB = btnCEn;
btnCEn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int m=2;
btnTopEn = ((Button) findViewById(m));
final Button finalBtnT = btnTopEn;
if (finalBtnT.getText().equals("")) {
String stGetText=finalBtnB.getText().toString();
finalBtnT.setText(stGetText);
break;
}
}
}
});
TableRow.LayoutParams lp = new TableRow.LayoutParams(100,100);
tr.addView(btnCEn, lp);
}
layout.addView(tr);
}
I wrote some code in OnClickListener event but none happen!
What is the value of str in the first loop ?
Also you are setting the text to a space .
btnTopEn.setText(" ");
And while checking you check for empty :
if (finalBtnT.getText().equals("")){
}
Try changing to
if (finalBtnT.getText().toString().trim().equals("")){
}

Change a different button when i click a button

I am trying to create a memory game but I can't find any way to change a x button when I press a y button. Here is my code.
I want to be able to handle different buttons when the private void gridButtonClicked is been used.
public class MainActivity2 extends ActionBarActivity {
private static final int NUM_ROWS =10 ;
private static final int NUM_COLS = 4;
Button buttons[][]=new Button[NUM_ROWS][NUM_COLS];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
populateButtons();
}
private void populateButtons() {
TableLayout table = (TableLayout) findViewById(R.id.tableForButtons);
for(int row=0; row < NUM_ROWS; row++){
TableRow tableRow=new TableRow(this);
tableRow.setLayoutParams(new TableLayout.LayoutParams( //we use this to fill the screen
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.MATCH_PARENT,
1.0f));
table.addView(tableRow);
for(int col=0; col < NUM_COLS; col++){
final int FINAL_COL=col;
final int FINAL_ROW=row;
Button button= new Button(this);
button.setLayoutParams(new TableRow.LayoutParams( //we use this to fill the screen
TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.MATCH_PARENT,
1.0f));
button.setText("" + col + "," + row); //text for every button
button.setPadding(0,0,0,0); //this is to make text visible even if the buttons are very small
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
gridButtonClicked(FINAL_COL,FINAL_ROW); //we need final because we can't pass variables from inner classes
}
});
tableRow.addView(button);
buttons[row][col]=button;
}
}
}
private void gridButtonClicked(int col, int row) {
Toast.makeText(this,"clicked",Toast.LENGTH_SHORT).show();
Button button=buttons[row][col];
// button.setBackgroundResource(R.drawable.abc_ab_share_pack_mtrl_alpha);
String id= (String) button.getText();
if(id.equals("1,2")) {
button.setText("" + col + ""); //change the button
}
if(id.equals("1")) {
button.setText("" + col + "," + row); //change the button
}
if(id.equals("2,1")) {
button.setText("" + col + ""); //change the button
}
}
Any help would be appreciated.
My suggestion is to create your own View (you can extends from a Button or ImageButton as well) and using an Adapter to fill up a GridView.
Afterwards you can control the behaviour or your View on its class.
I think this is what you are looking for. It is just the same as interacting with the first button. Let me know if I misunderstood your question, or if you need more information!
private void gridButtonClicked(int col, int row) {
Toast.makeText(this,"clicked",Toast.LENGTH_SHORT).show();
Button button=buttons[row][col];
int otherRow = ?;
int otherColumn = ?;
Button otherButton = buttons[otherRow,otherColumn];
otherButton.setText("Whatever you want");
// button.setBackgroundResource(R.drawable.abc_ab_share_pack_mtrl_alpha);
String id= (String) button.getText();
if(id.equals("1,2")) {
button.setText("" + col + ""); //change the button
}
if(id.equals("1")) {
button.setText("" + col + "," + row); //change the button
}
if(id.equals("2,1")) {
button.setText("" + col + ""); //change the button
}
}

Dynamically create button using data in array and setOnClicklistener

im trying to add the OnClickListener to the button that it generated by the value in array, but m fail to do so, any suggestion here?
long lprice = Long.parseLong(searchId.getText().toString());
List<String> buttonNameOne = dbc.getItemNameRbPrice(lprice);
List<String> buttonPriceOne = dbc.getPriceRbPrice(lprice);
List<String> buttonDateOne = dbc.getCurrentDateRbPrice(lprice);
for(int i = 0 ; i < buttonNameOne.size() ; i ++)
{
Button btn = new Button(this);
btn.setId(2000+i);
btn.setText(buttonNameOne.get(i) + i);
linearButton.addView(btn, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
Log.v("Value of element "+i, buttonNameOne.get(i));
Log.v("Value of element "+i, buttonPriceOne.get(i));
Log.v("Value of element "+i, buttonDateOne.get(i));
}
What you want to do is add the btn.setOnClickListener
for(int i = 0; i < buttonnameOne.size(); i++)
{
Button btn = new Button(this);
btn.setId(2000+i);
btn.setText(buttonNameOne.get(i) + i));
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(view v) {
// TODO Whatever you want onclick to do
}
});
//Log stuff
linearButton.addView(btn, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
}

Dynamically creating ImageButtons and adding them to layout with OnClickListeners

I'm trying to dynamically and programmatically create ImageButtons and add them to my Scrolling LinearLayout. I've been able to add them, but when I try to add onClickListeners to them, all their view ID's are -1; hence not being able to find out which button was clicked.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
OnClickListener imageClickListener;
imageClickListener = new OnClickListener(){
#Override
public void onClick(View v) {
System.out.println("id clicked: " + v.getId());
}
};
for (int i = 0; i<images.length; i++)
{
LinearLayout il = new LinearLayout(this);
il.setOrientation(LinearLayout.HORIZONTAL);
il.setMinimumHeight(LayoutParams.WRAP_CONTENT);
il.setMinimumWidth(LayoutParams.WRAP_CONTENT);
int imageid = 0;
ImageButton ib;
BitmapDrawable imagebd;
imageid = getResources().getIdentifier("drawable/" + images[i], null, getPackageName());
imagebd = resizeImage(imageid);
ib = new ImageButton(this);
ib.setClickable(true);
ib.setOnClickListener(imageClickListener);
ib.setImageDrawable(imagebd);
ib.setMinimumHeight(size);
ib.setMinimumWidth(size);
ib.setMaxHeight(size);
ib.setMaxWidth(size);
imageButtons.add(ib);
il.addView(ib);
System.out.println("id: " + ib.getId());
ll.addView(il);
}
this.setContentView(sv);
}
Why not call ib.setId(i) ?
If you want an id, you have to define it when you create the image button!
ImageButton ib = new ImageButton(this);
ib.setId(i);
Try this

Setting background image makes the button unclickable

I have created an array of buttons. When I set the background image to each button it becomes unlockable (disabled). Why this happen? Please, anyone, suggest it to me.
My code:
LinearLayout layoutVertical = (LinearLayout) findViewById(R.id.liVLayout);
LinearLayout rowLayout=null;
Button[][] buttons = new Button[6][7];
LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT,1);
for (int i = 0; i<6; i++)
{
rowLayout = new LinearLayout(this);
rowLayout.setWeightSum(7);
layoutVertical.addView(rowLayout,param);
for(int j=0;j<7;j++)
{
buttons[i][j]=new Button(this);
buttons[i][j].setText("1");
buttons[i][j].setBackgroundResource(R.drawable.but_blue_clicked);
rowLayout.addView(buttons[i][j],param);
buttons[i][j].setClickable(true);
}
}
}
There is no code adding listener to button. This is probably the problem.
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
Please look below code it helpful to you
LinearLayout layoutVertical = (LinearLayout) findViewById(R.id.liVLayout);
LinearLayout rowLayout = null;
Button[][] buttons = new Button[6][7];
LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1);
for (int i = 0; i < 6; i++) {
rowLayout = new LinearLayout(this);
rowLayout.setWeightSum(7);
layoutVertical.addView(rowLayout, param);
for (int j = 0; j < 7; j++) {
buttons[i][j] = new Button(this);
buttons[i][j].setText("1");
buttons[i][j].setBackgroundResource(R.drawable.btn_yes);
rowLayout.addView(buttons[i][j], param);
buttons[i][j].setClickable(true);
buttons[i][j].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(v.getContext(), "Click Button", 5000).show();
}
});
}
}
very silly mistake.. you forget to add
btnNAme.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0)
{
//some code
}
});
this is good practice to make the Listener for array of buttons
for (int ImgBtnID = 0; ImgBtnID <=8; ImgBtnID++)
{
ImgBtnArray[ImgBtnID].setOnClickListener(myListener);
}
OnClickListener myListener = new View.OnClickListener() {
// #Override
public void onClick(View v) {//your code
}
}

Categories

Resources