OnClickListener and Table Layout - java

I have an Activity with two layouts, both implemented in R.layout.main. The first one is a Relative Layout with the app's main screen, and the other is a Table Layout, holding a kind of Preferences Screen. Normally, the first one is set to visible, and the second one to gone. By clicking a button I make the Relative Layout gone, and the Table Layout visible.
And here starts my problem, I wanted to set a OnClickListener to that Table Layout (which is actually an array of buttons).
I tried something like:
final TableLayout table = (TableLayout)findViewById(R.id.tab);
table.setOnClickListener(new OnClickListener(){
public void onClick(View arg){
Button clickedButton = (Button)arg;
String t = (String) clickedButton.getTag();
Toast toast = Toast.makeText(getApplicationContext(),t,Toast.LENGTH_SHORT);
toast.show();
}
});
Obviously, it doesn't work.
I'm quite new to Android programming, and I've been looking for a suitable solution for the whole day without any results.

It couldn't work because you are first trying to cast a TableLayout to a button...
if your TableLayout is only containing buttons you could do something like:
TableLayout yourRootLayout = findView....
int count = yourRootLayout.getChildCount();
for(int i = 0; i < count; i++){
View v = yourRootLayout.getChildAt(i);
if(v instanceof TableRow){
TableRow row = (TableRow)v;
int rowCount = row.getChildCount();
for (int r = 0; r < rowCount; r++){
View v2 = row.getChildAt(r);
if (v2 instanceof Button){
Button b = (Button)v2;
b.setOnClickListener(this);
}
}
}
}
and let your activity implement OnClickListener. Just copy your Existing onClick into Activity itself...

Related

How to identify EditText by its tag

I am trying to get the value out of a series of EditText views in my app with a for() loop, but when I call the getText() method, the app crashes. There are 9 EditTexts and they each have a Tag from 1-9, so I am trying to use the getIdentifier() method and search for each EditText using its Tag, and I think that's the part that's not working... Any thoughts here? Thanks in advance!
public void xCalculateProfits (View view){
for (int x = 1; x <= 9; x++){
EditText xCurrentBox = (EditText) findViewById(getResources().getIdentifier(Integer.toString(x),"tag",getPackageName()));
Toast.makeText(this, xCurrentBox.getText().toString(), Toast.LENGTH_SHORT).show();
}
}
I think you'r app crashed because xCurrentBox is null.
you can define an int array and in that you store id of each EditText and use for loop to access the all EditText.
of course you can find View with tag . but you must can access to root view.
for example i have a linear layout in my activity and i can use that to access child view by tag .
for example :
LinearLayout linearLayout = findViewById(R.id.linearLayout);
for(int i=1 ; i<=4 ; i++)
{
EditText et = linearLayout.findViewWithTag(i+"");
Toast.makeText(this , et.getText().toString() ,
Toast.LENGTH_SHORT).show();
}
To find view by its tag, use View#findViewWithTag("tag"). This is a method of a View class, so you have to call it on any layout below your EditTexts, for example root View:
View root = getWindow().getDecorView().getRootView();
for (int x = 1; x <= 9; x++){
EditText xCurrentBox = (EditText) root.findViewWithTag("" + i);
Toast.makeText(this, xCurrentBox.getText().toString(), Toast.LENGTH_SHORT).show();
}
However, if you created these EditTexts in layout .xml file (not generated dynamically), I would suggest creating an array containing their IDs, like so:
public int[] viewsIds = {
R.id.edit_text1,
R.id.edit_text2,
R.id.edit_text3,
R.id.edit_text4,
...
};
and then use it in your for loop
for (int x = 1; x <= 9; x++){
EditText xCurrentBox = (EditText) findViewById(viewsIds[i]);
Toast.makeText(this, xCurrentBox.getText().toString(), Toast.LENGTH_SHORT).show();
}
This way your code is safer as you can benefit from static typing with autogenerated R class

Looping through specific widgets

Suppose I have a Table layout and i have a button called 'add people' which dynamically adds a row with two EdiTexts in it each time I click it. now there is another button which is supposed to save the first editText values in database and Add(sum) all the values of second editText .in HTML is very straight forward I can simply add class attribute to both inputs and loop through each class name. but I have no idea how i am supposed to do it in android.
What about saving the references in two lists? Then you can simply iterate over the lists to either store the values in a db or to sum them.
original answer check
public void init(){
TableLayout tablelayout = (TableLayout) findViewById(R.id.displayLinear);
for (int i = 0; i <2; i++) {
//Dynamic Button
Button myButton = new Button(this);
myButton.setText("Push Me");
LinearLayout ll = (LinearLayout)findViewById(R.id.buttonlayout);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);
}
}

Is it possible to convert a table row into string in Android?

I am developing my first Android app. I have a table layout in my app, which will add rows dynamically. But, I want to convert the table rows into string. I tried "row.toString()" but I am not getting the expected result. Please find the following code snippet:
View view = null;
for(i = 0, j = tblayout.getChildCount(); i < j; i++)
{
view = tblayout.getChildAt(i);
TableRow rw = (TableRow)tblayout.getChildAt(i);
ColorDrawable viewColor = (ColorDrawable) view.getBackground();
int colorId = viewColor.getColor();
if(colorId == Color.parseColor("#E143ED23")) {
num ++;
//temCnt = view.toString();
temCnt = rw.toString();
}
}
Toast.makeText(getApplicationContext(),temCnt, Toast.LENGTH_LONG).show();
But it is not showing the actual table row data. It is showing some ids' or garbage value.
My requirement is:
I have 2 text boxes and 2 buttons. When the first button "Ok" is pressed the value inside the text boxes will be populated into the Table layout along with a checkbox. By default the row will be checked. But user can uncheck each items. After that, when the second button "Save All" is pressed, then it will search for all the table rows which are checked and it should insert the table rows into the my MS SQL table.
Is there any way for converting the table row into a string in Java? I really trapped on this. It would be very helpful if someone can help me on this.
Please help...
toString() is a very basic method in Java, C# and other programming languages. Java's Object class has a basic implementation for it and you can override this method in any class that inherits from Object (that is, every class whatsoever :)). I don't know if those that developed the TableRow class of Android have overridden this method. It could be that what you're getting is some unreadable, meaningless representation of a TableRow object.
Let's say you have a TextView called txtName within the TableRow, followed by a second TextView called txtNumber. You can get what you want by doing the following:
...
ColorDrawable viewColor = (ColorDrawable) view.getBackground();
int colorId = viewColor.getColor();
if(colorId == Color.parseColor("#E143ED23")) {
num ++;
//temCnt = view.toString();
TextView nameField = (TextView) rw.findViewById(R.id.txtName);
TextView numberField = (TextView) rw.findViewById(R.id.txtNumber);
temCnt = nameField.getText().toString() + ": " + numberField.getText().toString();
}
...

How to create setOnClickListener on an array of buttons in Java

I have a dynamic array of buttons and I would like to know how to handle the onclick on every button?I want also user give the number of buttons from an extra setup menu.I try the below code but give wrong results...How I can leave distance 10dp between buttons from java file? how I can use the handleOnClick method ?
LinearLayout ll = (LinearLayout)findViewById(R.id.buttonlayout2);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
lp.bottomMargin=10;
Button btn[] = new Button[oNumber];
for (int i=0;i<oNumber;i++){
btn[i] = new Button(this); // initialize it
//btn[i].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
btn[i].setText(oName[i]);
btn[i].setTextColor(Color.rgb(255 , 00 , 00));
btn[i].setId(i);
btn[i].setTag(Integer.valueOf(i));
// btn[i].setOnClickListener(handleOnClick(btn[i]));
// btn[i].setOnClickListener(this);
ll.addView(btn[i],lp);
}
for( int i = 0; i< btn.length; i++){
btn[i].setOnClickListener(new OnClickListener() {
public void onClick(View v){
//do something
//if(v.getId()==0)
Integer mp=((Integer) v.getTag()).intValue();
if( mp==0)
{
//its Button 1 do what ever u want
Toast.makeText(getApplicationContext(), "Extra button 0...", Toast.LENGTH_SHORT).show();
}
if(mp==1)
{
//its Button 2 do what ever u want its Button 2
Toast.makeText(getApplicationContext(), "Extra button 1...", Toast.LENGTH_SHORT).show();
}
}
});
}
Switch the line:
btn[i].setId(i);
with:
btn[i].setTag(Integer.valueOf(i));
Also switch:
v.getId()==1
with:
((Integer)v.getTag()).intValue()==1
For the margin you need to call requestLayout() after setMargins().

Force Close When Dynamically Creating Widget from XML in Android

I'm attempting to create a few radio buttons and add them a RadioGroup dynamically. When I use the LayoutInflater method of pulling in the xml and adding it to the current view, everything works fine. The correct radio buttons show up.
However when I try to cast the View that LayoutInflater.inflate returned to a RadioButton (so I can setText), I get a force close with a java.lang.ClassCastException.
for (int i = 0; i < options.length(); i++) {
JSONObject option = options.getJSONObject(i);
View option_view = vi.inflate(R.layout.poll_option, radio_group, true);
option_view.setId(i);
RadioButton rb = (RadioButton) option_view.findViewById(i);
rb.setText(option.getString("response"));
}
poll_option.xml:
<RadioButton xmlns:android="http://schemas.android.com/apk/res/android"
android:text="RadioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
The problem is you're not getting the views you think you're getting. LayoutInflater.inflate() called with a supplied root view means the view returned to you is THAT root view (not the inflated view). The method in which you are calling it inflates a new RadioButton and attaches it to the Group, but the return value (option_view) is the group itself, not the individual item. Since you need to play with the view before attaching it to the group, I'd recommend code like this (which works):
//I added these for posterity, I'm sure however you get these references is fine
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RadioGroup radio_group = new RadioGroup(this);
//Get the button, rename it, then add it to the group.
for(int i = 0; i < options.length(); i++) {
JSONObject option = options.getJSONObject(i);
RadioButton option_view = (RadioButton)vi.inflate(R.layout.poll_option, null);
option_view.setText(option.getString("response"));
radio_group.addView(button);
}
Editorial Note:
Just my $0.02, for such a simple layout, running this inflation process over and over in a loop may be a bit too much (inflation is expensive). You could easily create the same RadioButton in code, and add it with your LayoutParams, like:
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
for (int i = 0; i < options.length(); i++) {
RadioButton option_view = new RadioButton(this);
option_view.setText(option.getString("response"));
radio_group.addView(option_view, params);
}
This code I didn't test, but it should be pretty close :p
Hope that Helps!
You probably want to use findViewById and locate the radio button in the inflated view. Something like:
RadioButton rb = (RadioButton)option_view.findViewById(R.id.yourButtonId);
See http://developer.android.com/reference/android/view/View.html#findViewById(int)
you want to radiobutton.setId(INT)
and then later get it by findViewById() to get the button.
The setID(Int) should be used when you dynamically create the button. You can now access it later with findViewById.

Categories