Unable to select children (textview) of tableRow programmatically - android

I'm trying to print the value of the TextViews which are inside TableRows, using TableLayout#getChildAt(i).getChildAt(j).
When I try to log it using the above, logcat complains, saying that it's a View object and that it doesn't have the method I'm trying to use (getText()).
The only Views in the TableRows are TextViews.
// List<TextView> textViewBoxes...
private void createViews() {
...
tblLayout = new TableLayout(this);
tblRow01 = new TableRow(this);
...
for (int i = 0; i < 99; i++) {
TextView text = new TextView(this);
text.setText("Player " + i);
textViewBoxes.add(text);
}
tblRow01.addView(textViewBoxes.get(0));
...
tblLayout.addView(tblRow01);
...
// Print the contents of the first row's first TextView
Log.d(TAG, ("row1_tv1: " +
tblLayout.getChildAt(0).getChildAt(0).getText().toString));
...
}

Have you tried something like this?
TableRow row = (TableRow)tblLayout.getChildAt(0);
TextView textView = (TextView)row.getChildAt(XXX);
// blah blah textView.getText();
You can also do it in one line, but it sometimes looks ugly:
// wtf?
((TextView)((TableRow)tblLayout.getChildAt(0)).getChildAt(XXX)).getText();
Anyway... what you are doing here is casting the View to the specific type you want. You can do that without problems, since you are completely sure that each TableLayout's child is a TableRow, and you know that TableRow's children on XXX position is a TextView.

Related

How to break a line in between two textViews when both the textViews are having different styles programatically

I am building a cart view for an e-commerce app and I want to build a View in which my product name should be bold and of bigger text size and under that a small description of the product which is of smaller text size should be there but I am facing the problem to break a line in between these two textViews. My code is something like this
for (int j=0;j< productsize;j++){
String pName = ct.getProducts(j).getProductName();
int pPrice = ct.getProducts(j).getProductPrice();
String desc = ct.getProducts(j).getProductDesc();
LinearLayout la = new LinearLayout(this);
la.setOrientation(LinearLayout.HORIZONTAL);
TextView tv = new TextView(this);
tv.setText(" " + pName + " ");//first textView
tv.setTypeface(null, Typeface.BOLD);
tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22F);
la.addView(tv);
TextView des = new TextView(this);//second textView
des.setText("" + desc + "");
la.addView(des);
final Button btn1 = new Button(this);
btn1.setId(j+1);
btn1.setText("Add to Cart");
btn1.setLayoutParams(params);
final int index = j;
btn1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("TAG", "index:"+index);
ModelProducts productsObject = ct.getProducts(index);
if(!ct.getCart().CheckProductInCart(productsObject)){
btn1.setText("Item Added");
ct.getCart().setProducts(productsObject);
Toast.makeText(getApplicationContext(), "New CartSize:" +ct.getCart().getCartsize(),Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Products"+(index+1)+"Already Added",Toast.LENGTH_LONG ).show();
}
}
});
la.addView(btn1);
layout.addView(la);
}
Can anyone help me with this please thanks in advance.
Try changing this line:
la.setOrientation(LinearLayout.HORIZONTAL);
to this:
la.setOrientation(LinearLayout.VERTICAL);
Updated:
If you want the two TextViews aligned vertically and the Button horizontally aligned, then you need to use a RelativeLayout or two LinearLayouts.
Using two LinearLayouts you may try to form the structure like this:
<LinearLayout with horizontal orientation....
.....
<LinearLayout with vertical orientation....
...
<TextView.....
<TextView .....
</LinearLayout>
<Button .....
</LinearLayout>
In this way your root LinearLayout with horizontal orientation will have two child i.e the LinearLayout with vertical orientation and the Button.
I hope this will help you.
Try changing this
la.setOrientation(LinearLayout.HORIZONTAL);
to this
la.setOrientation(LinearLayout.VERTICAL);
Though, I don't know if it's necessary to build your UI programmatically, but you can easily/better implement that title-subtitle textview using a layout XML, where you can get a preview of what your UI looks like.

create multiple runtime textview in android

I have code in eclipse for create multiple TextView in multiple rows but when run the application items don't show, please help me how to fix it.
This is my code:
public void createInputBoxes(Activity gameplay, int colnums, int rownums, TableLayout.LayoutParams lparams, TableLayout puzzlelayout) {
TextView[][] puzcels = new TextView[colnums][];
puzzlelayout.removeAllViews();
for(int c=0; c<colnums; c++)
{
puzcels[c]=new TextView[rownums];
TableRow tr = new TableRow(gameplay);
tr.setLayoutParams(lparams);
for(int r=0; r<rownums; r++)
{
puzcels[c][r] = new TextView(gameplay);
puzcels[c][r].setLayoutParams( lparams);
puzcels[c][r].setId(tvid);
puzcels[c][r].setText("?");
tvid++;
puzcels[c][r].setBackgroundColor(0xffffb90f);
tr.addView(puzcels[c][r]);
}
puzzlelayout.addView(tr,lparams);
}
}
You are using TableLayout.LayoutParams params for all of your views - TableLayout, TableRow and TextView. That won't work for those last two. You need to give them params that work for them:
Dynamically filling a Table Layout with Table Rows

android TextView arrays

I am making a word game in which each a user has multiple guesses, each one made up of multiple TextViews. So far my code reads:
TextView[] guess1 = new TextView[numTextViews];
guess1[0] = (TextView) findViewById(R.id.Guess1_1);
guess1[1] = (TextView) findViewById(R.id.Guess1_2);
guess1[2] = (TextView) findViewById(R.id.Guess1_3);
guess1[3] = (TextView) findViewById(R.id.Guess1_4);
guess1[4] = (TextView) findViewById(R.id.Guess1_5);
with the xml looking like:
<TextView
android:id="#+id/Guess1_1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:text="#string/guessChar" />...
which repeats with android:id= changing.
I am going to be repeating myself if I type out TextView[] guess2 and all its elements.
What is a better way to go about this?
Would it be better to create all the TextViews programmatically as they are so similar?
This is how you can iterate through your views without the use of ids in repetitive code:
LinearLayout ll = (LinearLayout) findViewById(R.id.layout_containing_textviews);
for (int i = 0; i < ll.getChildCount(); i++) {
if (ll.getChildAt(i).getClass() == TextView.class) {
guess1[i] = (TextView)ll.getChildAt(i);
}
}
Make sure to tweak this in case you have non-TextView views since the i index will not be consecutive in that case. You can use another counter just for the TextViews.
Now if your layout has only TextViews, you don't even need an array. You can use that layout as a container/array the way it's used in the snipped above.
Do you know what is the amount of guesses for each text view?
I would suggest you to use reflection
Class clazz = R.id.class; // get the R class
Field f = clazz.getField("Guess1_" + "1");
int id = f.getInt(null); // pass in null, since field is a static field.
TextView currcell = (TextView) findViewById(id);
in this case it will bring the Guess1_1
for you case:
for (int i =0; i < numTextViews; i++)
{
Class clazz = R.id.class;
Field f = clazz.getField("Guess1_" + Integer.toString(i+1));
int id = f.getInt(null);
guess[i] = (TextView)findViewById(id);
}
but this only bring you the first array of Guess1 you need to convert it to generic code..
so some problems can be occur.. so read it with the xml as you have right now would be the easiest way..
Edit:
If the all textView have the same attributes you can also create it programmatically
LinearLayout view = new LinearLayout(this); // create new linear layout
view.setOrientation(LinearLayout.HORIZONTAL); // optional.. so the
// view will be horizontaly
view.setLayoutParams(new LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT)); // set the layout
// height and width
for (int i = 0; i < numOf ; i ++)
{
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
guess[i] = new TextView();
guess[i].setLayoutParams(lp);
guess[i].setID(i+1);
}
You could either create the textViews programmatically (and use inflate if you wish to use some xml too), or you could use the getIdentifier method , for example:
private static final String ID_FORMAT="Guess1_%d";
...
for(int i=0;i<10;++i)
{
String id=String.format(FORMAT,i);
TextView tv = (TextView) findViewById(getResources().getIdentifier(id, "id", getPackageName()));
//...
}
same goes if you wish to do a loop within a loop.
If the layout has a lot of views, I would suggest using an adapterView (listView,gridView,...) instead, and avoid creation of so many views (either programmatically or by xml).

Android: adding multiple Views programmatically

I want to add a LinearLayout wrapped around a TextView and Button programmatically. I want it to take a String array and then using the length of the string array, add that many TextViews each with their own button.
So first:
String [] s = { .... the values ....}
int sL = s.length;
TextView t1 = new TextView (this);
// then somehow create t2, t3... etc. matching the length of the String array.
Is this the best way to do this or is there another way to do this? For some context, it's a quiz app and I've created a list of categories inside resources as values and I'm trying to programmatically get my app to create as many TextViews as there are categories then set each TextView to each category then get each button to take the user to that category of questions.
You are starting it right, just do a for loop and add textviews to your linearlayout.
// You linearlayout in which you want your textview
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.mylayout);
linearLayout.setBackgroundColor(Color.TRANSPARENT);
String [] s = { .... the values ....}
int sL = s.length;
TextView textView = null;
// For later use if you'd like
ArrayList<TextView> tViews = new ArrayList<TextView>();
for (int i = 0; i < sL; i++)
{
textView = new TextView(this);
textView.setText(s[i]);
linearLayout.addView(textView);
tViews.add(textView);
}
There is nothing wrong with this way of doing it. If you want to use these textview later on (set text for them or something) store them in an Array of some kind. Edited code
You can do the following:
for(int i=0;i<s.length;i++){
TextView t=new TextView(this);
t.setText(s[i]);
yourLinearLayout.addView(t);
}
But I really think that using a ListView would be better for performance ;)

Android Table Layout with 5x5 dimension

I'm still new in android programming, what I'm trying to do is, I want to create 5x5 dimension TableLayout. I know this can be done by using GridView BaseAdapter suing Inflate service. But for this one i try to apply using table layout. Below is the code. I create new instance of TableLayout, and new instance of Table row. On each table row, I created instance of 5 TextView. But once I open in emulator or in my phone, there is no TableRow created, it just empty blank Table Layout. Also there is no exception was thrown.
GridView navIcon = (GridView) findViewById(R.id.content);
navIcon.setAdapter(new ImageAdapter(this));
navIcon.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View v, int position,long id) {
// TODO Auto-generated method stub
if (position==0){
try{
TableLayout calgrid = (TableLayout) findViewById(R.id.gridtable);
Context ctxt = v.getContext();
TextView[] tView = new TextView[25];
calgrid = new TableLayout(ctxt);
int dip = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,(float) 1, getResources().getDisplayMetrics());
int counter=1;
TableRow[] tr = new TableRow[5];
for(int j=0;j<5;j++){
tr[j] = new TableRow(ctxt);
for(int i=0;i<5;i++){
tView[i] = new TextView(ctxt);
tView[i].setText(String.valueOf(counter));
tView[i].setTextSize(15);
counter+=1;
tView[i].setWidth(50 * dip);
tView[i].setPadding(20*dip, 0, 0, 0);
tView[i].setTextColor(Color.rgb( 100, 200, 200));
Toast.makeText(getApplicationContext(), "tView["+i+"] value " + String.valueOf(tView[i].getText()), Toast.LENGTH_SHORT).show();
tr[j].addView(tView[i], 50, 50);
}
calgrid.addView(tr[j]);
}
}catch(Exception e){
Log.e("MainActivity", "Error in activity", e);
Toast.makeText(getApplicationContext(),e.getClass().getName() + " " + e.getMessage(),Toast.LENGTH_LONG).show();
}
}
}
});
First of all, it is a mistake to do calgrid = (TableLayout) findViewById(R.id.gridtable); and then calgrid = new TableLayout(ctxt);, which basically says find this view now assign this variable to something completely different. Remove the second statement and it will load the table from xml which is what you want.
Second, I think it would be a good idea to simplify things for yourself because there is a lot going on here. Instead of doing all this work inside an onClick listener, do it in the onCreate method itself. Also, you seem to be using the Context from the GridView, which seems odd. Perhaps if you posted your xml layout file it could help explain what you are trying to do?
There is also a problem with indices in the array of TextViews, as tView[i] will only assign items up to 5 but the array contains 25 items. Try using tView[(j*5)+i] instead. I don't think this is causing your problems but just make sure you are assigning your items correctly.
Here is an example of how to do something along the lines of what you want
setContentView(R.layout.grid);
TableLayout tl = (TableLayout) findViewById(R.id.gridtable);
for (int j = 0; j < 5; j++) {
TableRow tr = new TableRow(this);
tr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
for (int i = 0; i < 5; i++) {
TextView tView = new TextView(this);
tView.setText("TEXT" + String.valueOf((j * 5) + i + 1));
tView.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
tr.addView(tView);
}
tl.addView(tr, new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
}
and grid.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridtable"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</TableLayout>
Once you get it working in the activity itself you can try to put it inside a listener attached to a GridView. Hope this helps!

Categories

Resources