Change a different button when i click a button - android

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
}
}

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("")){
}

How to add radiobutton to each cell in table layout

I want to add radiobuttons for every cell in given below table and get their position based on row and column, how to achieve it? Kindly share your views. Thanks in advance. I have commented the code where i was adding text to each cells, may be at the same place we can add radiobuttons
Below is working code :
public class MainActivity extends Activity {
RelativeLayout rl;
RadioGroup rg;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] row = { "AA", "BB", "CC", "DD", "EE", "FF", "GG" };
String[] column = { "Col 1", "Col 2", "Col 3", "Col 4", "Col 5", "Col 6" };
int rl = row.length;
int cl = column.length;
Log.d("--", "R-Lenght--" + rl + " " + "C-Lenght--" + cl);
ScrollView sv = new ScrollView(this);
TableLayout tableLayout = createTableLayout(row, column, rl, cl);
HorizontalScrollView hsv = new HorizontalScrollView(this);
hsv.addView(tableLayout);
sv.addView(hsv);
setContentView(sv);
}
public void makeCellEmpty(TableLayout tableLayout, int rowIndex, int columnIndex) {
// get row from table with rowIndex
TableRow tableRow = (TableRow) tableLayout.getChildAt(rowIndex);
// get cell from row with columnIndex
TextView textView = (TextView) tableRow.getChildAt(columnIndex);
// make it black
textView.setBackgroundColor(Color.BLACK);
}
public void setHeaderTitle(TableLayout tableLayout, int rowIndex,
int columnIndex) {
// get row from table with rowIndex
TableRow tableRow = (TableRow) tableLayout.getChildAt(rowIndex);
// get cell from row with columnIndex
TextView textView = (TextView) tableRow.getChildAt(columnIndex);
textView.setText("Hello");
}
private TableLayout createTableLayout(String[] rv, String[] cv,
int rowCount, int columnCount) {
// 1) Create a tableLayout and its params
TableLayout.LayoutParams tableLayoutParams = new TableLayout.LayoutParams();
TableLayout tableLayout = new TableLayout(this);
tableLayout.setBackgroundColor(Color.BLACK);
// 2) create tableRow params
TableRow.LayoutParams tableRowParams = new TableRow.LayoutParams();
tableRowParams.setMargins(1, 1, 1, 1);
tableRowParams.weight = 1;
for (int i = 0; i < rowCount; i++) {
// 3) create tableRow
TableRow tableRow = new TableRow(this);
tableRow.setBackgroundColor(Color.BLACK);
final RadioButton[] rb = new RadioButton[10];
rl=(RelativeLayout) findViewById(R.id.rl);
rg=new RadioGroup(this);
for (int j = 0; j < columnCount; j++) {
// 4) create textView
TextView textView = new TextView(this);
// textView.setText(String.valueOf(j));
textView.setBackgroundColor(Color.WHITE);
textView.setGravity(Gravity.CENTER);
String s1 = Integer.toString(i);
String s2 = Integer.toString(j);
String s3 = s1 + s2;
int id = Integer.parseInt(s3);
Log.d("TAG", "-___>" + id);
if (i == 0 && j == 0) {
textView.setText("0==0");
} else if (i == 0) {
Log.d("TAAG", "set Column Headers");
textView.setText(cv[j - 1]);
} else if (j == 0) {
Log.d("TAAG", "Set Row Headers");
textView.setText(rv[i - 1]);
} else {
/*textView.setText("" + id);
// check id=23
if (id == 23) {
textView.setText("ID=23");
}*/
//Add Radiobuttons here
}
// 5) add textView to tableRow
tableRow.addView(textView, tableRowParams);
}
// 6) add tableRow to tableLayout
tableLayout.addView(tableRow, tableLayoutParams);
}
return tableLayout;
}
}
please use listview instead of table layout
ListView listView = (ListView) view.findViewById(R.id.listview);
// values is a StringArray holding some string values.
CustomAdapter customAdapter = new CustomAdapter (getActivity(), values);
listView.setAdapter(customAdapter );
Use multi-dimensional array of Radio Button or group or whatever you want...
RadioButton[][] rb = new RadioButton[][];
Use above statement for declaring it and for accessing it use two loops which are nested. One loop is nested in another.
for(int i=0;i<=5;i++)
{
for (int j=0;j<=5;j++)
{
rb[i][j] = new RadioButton(this);
}
}

pass value from stringbuilder to textview

I am trying to get words from several EditTexts and display them using TextView without using any layout. But the program is force closed every-time I run it.
LOGCAT: java.lang.RuntimeException: Unable to instantiate activity
ComponentInfo{com.example.tablelayout/com.example.tablelayout.MainActivity}:
java.lang.NullPointerException
public class MainActivity extends Activity {
private List<EditText> editTextList = new ArrayList<EditText>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout linearLayout = new LinearLayout(this);
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(FILL_PARENT, WRAP_CONTENT);
linearLayout.setLayoutParams(params);
linearLayout.setOrientation(VERTICAL);
int count = 10;
linearLayout.addView(tableLayout(count));
linearLayout.addView(submitButton());
setContentView(linearLayout);
}
private Button submitButton() {
Button button = new Button(this);
button.setHeight(WRAP_CONTENT);
button.setText("Submit");
button.setOnClickListener(submitListener);
return button;
}
TextView txt=new TextView(this);
// Access the value of the EditText
private View.OnClickListener submitListener = new View.OnClickListener() {
public void onClick(View view) {
StringBuilder stringBuilder = new StringBuilder();
for (EditText editText : editTextList) {
stringBuilder.append(editText.getText().toString());
}
txt.setText(stringBuilder.toString().trim());
}
};
// Using a TableLayout as it provides you with a neat ordering structure
private TableLayout tableLayout(int count) {
TableLayout tableLayout = new TableLayout(this);
tableLayout.setStretchAllColumns(true);
int noOfRows = count / 5;
for (int i = 0; i < noOfRows; i++) {
int rowId = 5 * i;
tableLayout.addView(createOneFullRow(rowId));
}
int individualCells = count % 5;
tableLayout.addView(createLeftOverCells(individualCells, count));
return tableLayout;
}
private TableRow createLeftOverCells(int individualCells, int count) {
TableRow tableRow = new TableRow(this);
tableRow.setPadding(0, 10, 0, 0);
int rowId = count - individualCells;
for (int i = 1; i <= individualCells; i++) {
tableRow.addView(editText(String.valueOf(rowId + i)));
}
return tableRow;
}
private TableRow createOneFullRow(int rowId) {
TableRow tableRow = new TableRow(this);
tableRow.setPadding(0, 10, 0, 0);
for (int i = 1; i <= 5; i++) {
tableRow.addView(editText(String.valueOf(rowId + i)));
}
return tableRow;
}
private EditText editText(String hint) {
EditText editText = new EditText(this);
editText.setId(Integer.valueOf(hint));
editText.setHint(hint);
editTextList.add(editText);
return editText;
}
}
TextView txt=new TextView(this);
you can't declare and initialize a class member View at the same time, because the Context is not yet valid
change it to:
public class MainActivity extends Activity {
private List<EditText> editTextList = new ArrayList<EditText>();
private TextView txt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
txt = new TextView(this);
// other code
also I noticed that you are not adding this View to any of the containers that your provided to setContentView. The suggestion will fix the crash but you will not see the TextView's content
Exception shows problem is in your manifest file.
Your package name is manifest tag and your activity are in different locations.

Click Event On Dynamically Added TextViews in 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);

Getting dynamically added checkbox ID in Android

I'm adding a checkbox in my application dynamically, and I want to delete the records which are checked. But, I'm not getting the ID of the checkbox. How can I do this?
Code:
package com.my.StudentInfoManagement;
public class ListData extends Activity{
DataHelper dh;
TableLayout tb;
CheckBox[] ch=new CheckBox[50];
EditText ed;
int a[]=new int[50];
int k=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.listdataxml);
dh=new DataHelper(this);
System.out.println("in list data");
List<String> names= this.dh.selectAll();
ed=(EditText) findViewById(R.id.ed_id);
tb=(TableLayout) findViewById(R.id.table);
int i,j=1;
TextView name1 = null,id,dob,gender,branch,email,address,mobile;
String name11,id1 = null,dob1,gender1,branch1,email1,address1,mobile1;
TableRow tr=new TableRow(this);
tr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
TextView tv=new TextView(this);
String c = null;
String data[]=new String[50];
int cnt=0;
for(String name:names)
{
if((!name.equals("-999")))
{
data[cnt]=name;
cnt++;
System.out.println("........."+name);
}
else
{
cnt=0;
name1=new TextView(this);
name1.setText(data[1]+" ");
id=new TextView(this);
id.setText(data[0]+" ");
System.out.println("ID is...."+data[0]);
dob=new TextView(this);
dob.setText(data[3]+" ");
gender=new TextView(this);
gender.setText(data[2]+" ");
branch=new TextView(this);
branch.setText(data[4]+" ");
mobile=new TextView(this);
mobile.setText(data[5]+" ");
email=new TextView(this);
email.setText(data[6]+" ");
address=new TextView(this);
address.setText(data[7]+" ");
tr=new TableRow(this);
tr.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
ch[k]=new CheckBox(this);
System.out.println("sysout");
i=Integer.parseInt(data[0]);
ch[k].setId(i);
tr.addView(ch[k]);
a[k++]=i;
tr.addView(id);
tr.addView(name1);
tr.addView(dob);
tr.addView(gender);
tr.addView(branch);
tr.addView(mobile);
tr.addView(email);
tr.addView(address);
tb.addView(tr,new TableLayout.LayoutParams( LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
j++;
System.out.println("count"+j);
}
}
}
public void delete(View v){
System.out.println("In delete");
int bb=k,id ;
for (int i=0; i <k; i++)
{
final int j = a[i];
System.out.println("in for loop"+j);
ch[j].setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
System.out.println("Checked ID :: " + ch[j].getId());
}
});
}
System.out.println("00000000000000000..."+id);
dh.deleteData(id);
}
}
strong textJust take a global variable
int chkId = 1001;
then at time of adding CheckBox dynamically, set its id as
ch.setId(++chkId);
then at time of deleting CheckBox, you can get id of Checked CheckBox simple by using
getId()
methhod
See Following Demo:
public class ChkBoxesActivity extends Activity {
int chId = 1000;
int chPos = -1;
LinearLayout ll;
String[] names = {"Tom", "Dick", "Keanu", "Harry", "Katrina", "Peter", "Julia", "Emma"};
CheckBox[] ch;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ll = (LinearLayout) findViewById(R.id.ll);
ch = new CheckBox[names.length];
for(int i=0; i<names.length; i++) {
ch[i] = new CheckBox(this);
ch[i].setId(chId++);
System.out.println("CHID :: "+chId);
System.out.println("I :: "+i);
ch[i].setText(names[i]);
ll.addView(ch[i]);
}
for (int i = 0; i < names.length; i++) {
final int j = i;
ch[j].setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
System.out.println("Checked ID :: " + ch[j].getId());
}
});
}
}
}
Views added dynamically do not have an ID until you specifically set them. So you need to call view.setId() on the view when you're adding to your layout, else you won't be able to reference it with view.getId().
I experienced a similar issue a while back when trying to dynamically create a RelativeLayout and positions the inner views relative to each other; they wouldn't align how they should have because the ID's didn't exist until I explicitly set one for them.
Also, why are you doing this:
ch.getId();
ch.setId(1);
That makes absolutely no sense. Take it out.
And also, you're going to need a reference linking the CheckBox to the View you want to delete. In this case, I would make a new ArrayList of Objects that have both a CheckBox and a View inside of it, IE.
public Class MyRow{
CheckBox c;
View v;
public MyRow() { }
}
Then when adding your views dynamically, add them to your MyRow or whatever class, then add that class to an ArrayList, and boom, you now have references between them and can remove the correct ones.

Categories

Resources