Add clickable textview to table layout dynamically - android

Add clickable textview to table layout dynamically
TextView Delete = new TextView(this);
Delete.setText("Delete");
Delete.setClickable(true);
Delete.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
TransDelete(ac);
}
});
This is my row added dynamically.
public void TransDelete(final String TransID) {
class TransDeleteClass extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
Toast.makeText(ViewTransactions.this, httpResponseMsg.toString(), Toast.LENGTH_LONG).show();
finish();
}
#Override
protected String doInBackground(String... params) {
// Sending Trans id.
hashMap.put("TransID", params[0]);
finalResult = httpParse.postRequest(hashMap, HttpUrlDeleteRecord);
return finalResult;
}
}
TransDeleteClass TransDeleteClass = new TransDeleteClass();
TransDeleteClass.execute(TransID);
}
This is my onclick function. I tried to click my textview while launching the mulator but the textview does not respond to onclick . I have seen other forums but as I need to pass in my TransID which is not the id i show on screen. For example , I tried filtering the data and although the screen shows numbers added in numeric order, it is not the case for the database i am using.
Edit:
<ScrollView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fillViewport="true"
android:scrollbars="none"
android:layout_below="#+id/textView1">
<TableLayout android:layout_width="wrap_content"
android:layout_height="0dp"
android:stretchColumns="1,1,1"
android:id="#+id/maintable" >
</TableLayout>
</ScrollView>
This is my xml page but the table pops up perfectly.
I have chosen to add my headers of the table layout dynamically too.
void addHeader(){
/** Create a TableRow dynamically **/
tr = new TableRow(this);
/** Creating a TextView to add to the row **/
label = new TextView(this);
label.setText("ID");
label.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT));
label.setPadding(5, 5, 5, 5);
label.setBackgroundColor(Color.RED);
LinearLayout Ll = new LinearLayout(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT);
params.setMargins(5, 5, 5, 5);
Ll.setPadding(10, 5, 5, 5);
Ll.addView(label,params);
tr.addView((View)Ll); // Adding textView to tablerow.
Just a part of my header of the table as adding more codes would require more description.

final TextView[] myTextViews = new TextView[N]; // create an empty array;
for (int i = 0; i < N; i++) {
// create a new textview
final TextView rowTextView = new TextView(this);
// set some properties of rowTextView or something
rowTextView.setText("This is row #" + i);
// add the textview to the tablelayout
yourtable.addView(rowTextView);
// save a reference to the textview for later
myTextViews[i] = rowTextView;
}

Related

ArrayList data passed to a second Activity is not showing in a TableLayout there

I'm trying to send a sample ArrayList to a second Activity so that it can be displayed in a TableLayout.
My MainActivity class:
public class MainActivity extends AppCompatActivity {
public ArrayList<String> al = new ArrayList<>();
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.b);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
al.add("Add");
al.add("Sub");
Intent i = new Intent(view.getContext(),two.class);
i.putStringArrayListExtra("al", al);
startActivity(i);
}
});
}
}
The activity_main layout contains a Button that opens the next Activity, which contains a TableLayout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:stretchColumns="0,1"
android:id="#+id/main_table" android:layout_weight="1"
android:layout_height="wrap_content" android:layout_width="match_parent">
</TableLayout>
</LinearLayout>
In the second Activity, the ArrayList is being traversed to display the data in the TableLayout.
I guess the ArrayList is not being transfered properly to the next Activity.
public class two extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two);
Intent i = getIntent();
ArrayList<String> al = i.getStringArrayListExtra("al");
TableLayout tl = (TableLayout) findViewById(R.id.main_table);
TableRow tr_head = new TableRow(this);
//tr_head.setId(11);
// tr_head.setBackgroundColor(Color.GRAY);
int co=0;
for(String k:al)
{
co++;
TableRow tr = new TableRow(this);
tr.setId(co);
tr.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.FILL_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
TextView tv = new TextView(this);
tv.setText(k);
tv.setPadding(2, 0, 5, 0);
tr_head.addView(tv);
tl.addView(tr, new TableLayout.LayoutParams(
TableLayout.LayoutParams.FILL_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
}
}
}
ArrayList is being sent properly there is nothing wrong with that.
Also LayoutParams for TableRow isn't needed, add LayoutParams on TextView instead.
tr_head is not needed also if you have already defined Layout for TableLayout there is no need to give LayoutParams here:
tl.addView(tr, new TableLayout.LayoutParams(
TableLayout.LayoutParams.FILL_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
tl.addView(tr) will do just fine.
Try using the below code, this works fine by me!
public class two extends AppCompatActivity { #Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two);
Intent i = getIntent();
ArrayList<String> al = i.getStringArrayListExtra("al");
TableLayout tl = (TableLayout) findViewById(R.id.main_table);
int co=0;
for(String k:al)
{
co++;
TableRow tr = new TableRow(this);
tr.setId(co);
TextView tv = new TextView(this);
tv.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,TableRow.LayoutParams.WRAP_CONTENT,1.0f));
tv.setText(k);
tv.setPadding(2, 0, 5, 0);
tr.addView(tv);
tl.addView(tr);
}}}

Alignment setting in Dynamic TableLayout

I want to add x rows when user press the add button and in one of the row user enters no of types i.e. in edittext then according to that i need to populate that many no.of rows in two columns below that .. these columns alignment is missing..
LAYOUT
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add requirefields" />
<ScrollView
android:id="#+id/scrolllayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/button1"
android:layout_marginLeft="10dp" >
<TableLayout
android:id="#+id/tablelayout"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TableLayout>
</ScrollView>
</RelativeLayout>
ACTIVITY:-
public class MainActivity extends Activity {
Button addBtn;
TableLayout mTable;
TableLayout timingsTable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addBtn = (Button) findViewById(R.id.button1);
mTable = (TableLayout) findViewById(R.id.tablelayout);
addBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "btnonclicklistener",
Toast.LENGTH_LONG).show();
createTable();
}
});
}
public void createTable() {
// mTable.setColumnShrinkable(1, true);
mTable.setStretchAllColumns(true);
mTable.setShrinkAllColumns(true);
TableRow rowMName = new TableRow(MainActivity.this);
TableRow rowDescription = new TableRow(MainActivity.this);
TableRow rowType = new TableRow(MainActivity.this);
TableRow rowTimesADay = new TableRow(MainActivity.this);
TableRow rowTimings = new TableRow(MainActivity.this);
TableRow rowNoofTimings = new TableRow(MainActivity.this);
TextView mNametv = new TextView(MainActivity.this);
mNametv.setText("MNAME");
TextView descriptiontv = new TextView(MainActivity.this);
descriptiontv.setText("Description");
TextView typetv = new TextView(MainActivity.this);
typetv.setText("TYPE");
TextView timesAdaytv = new TextView(MainActivity.this);
timesAdaytv.setText("TimesADay");
TextView timingstv = new TextView(MainActivity.this);
timingstv.setText("Timings");
rowMName.addView(mNametv);
rowDescription.addView(descriptiontv);
rowType.addView(typetv);
rowTimesADay.addView(timesAdaytv);
rowTimings.addView(timingstv);
EditText etMName = new EditText(MainActivity.this);
EditText etDescription = new EditText(MainActivity.this);
EditText etType = new EditText(MainActivity.this);
final EditText etTimesAday = new EditText(MainActivity.this);
// EditText etTimings = new EditText(MainActivity.this);
timingsTable = new TableLayout(MainActivity.this);
TextView dosagetv = new TextView(MainActivity.this);
dosagetv.setText("Dosage");
rowMName.addView(etMName);
rowDescription.addView(etDescription);
rowType.addView(etType);
rowTimesADay.addView(etTimesAday);
rowNoofTimings.addView(timingsTable);
rowTimings.addView(dosagetv);
etTimesAday.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if (!s.toString().equals("")) {
int length = Integer.parseInt(s.toString());
if (length >= 1) {
timingsTable.removeAllViews();
timingsTable.setVisibility(View.VISIBLE);
dynamicEditBox(etTimesAday.getText().toString());
Toast.makeText(getBaseContext(), "if condition",
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getBaseContext(), "else condition",
Toast.LENGTH_SHORT).show();
timingsTable.setVisibility(View.GONE);
timingsTable.removeAllViews();
if (s.equals("")) {
etTimesAday.setText("");
}
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
mTable.addView(rowMName);
mTable.addView(rowDescription);
mTable.addView(rowType);
mTable.addView(rowTimesADay);
mTable.addView(rowTimings);
mTable.addView(rowNoofTimings);
}
public void dynamicEditBox(String id) {
timingsTable.setStretchAllColumns(true);
timingsTable.setShrinkAllColumns(true);
for (int i = 0; i < Integer.parseInt(id); i++) {
TableRow tr = new TableRow(MainActivity.this);
tr.setLayoutParams(new TableLayout.LayoutParams(
TableLayout.LayoutParams.WRAP_CONTENT,
TableLayout.LayoutParams.WRAP_CONTENT));
TableRow.LayoutParams parms = new TableRow.LayoutParams(
TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT);
TextView ed = new TextView(getApplication());
ed.setInputType(InputType.TYPE_CLASS_NUMBER);
ed.setLayoutParams(parms);
ed.setId(i);
ed.setHint("enter number");
ed.setBackgroundColor(Color.DKGRAY);
tr.addView(ed);
EditText b = new EditText(getApplication());
b.setLayoutParams(new TableRow.LayoutParams(
TableLayout.LayoutParams.WRAP_CONTENT,
TableLayout.LayoutParams.WRAP_CONTENT));
b.setId(i);
b.setBackgroundColor(Color.LTGRAY);
b.setText("dosage");
tr.addView(b);
TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(10, 10, 10, 0);
timingsTable.setLayoutParams(layoutParams);
timingsTable.addView(tr);
}
}
}
Currently i'm getting as follows..
I need to adjust those timings and dosage columns accordingly.help me in setting this alignment..
After making below changes in the dynamicEditBox method i got the alignment
public void dynamicEditBox(String id) {
timingsTable.setStretchAllColumns(true);
timingsTable.setShrinkAllColumns(true);
for (int i = 0; i < Integer.parseInt(id); i++) {
TableRow tr = new TableRow(MainActivity.this);
tr.setLayoutParams(new TableLayout.LayoutParams(
TableLayout.LayoutParams.WRAP_CONTENT,
TableLayout.LayoutParams.WRAP_CONTENT));
TableRow.LayoutParams parms = new TableRow.LayoutParams(0,
TableRow.LayoutParams.WRAP_CONTENT, 1f);
parms.setMargins(5, 5, 5, 5);
TextView tv = new TextView(getApplication());
tv.setLayoutParams(parms);
tv.setWidth(50);
tv.setPadding(20, 5, 5, 5);
tv.setId(i);
tv.setHint("10:25am");
tv.setBackgroundColor(Color.LTGRAY);
tr.addView(tv);
EditText et = new EditText(getApplication());
et.setLayoutParams(parms);
et.setPadding(5, 5, 5, 5);
et.setGravity(Gravity.CENTER);
et.setRawInputType(Configuration.KEYBOARD_12KEY);
et.setInputType(InputType.TYPE_CLASS_NUMBER);
et.setId(i);
et.setBackgroundColor(Color.LTGRAY);
et.setHint("dosage");
tr.addView(et);
TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(0,
TableRow.LayoutParams.WRAP_CONTENT, 1f);
layoutParams.setMargins(-15, 10, 0, 0);
timingsTable.setLayoutParams(layoutParams);
timingsTable.addView(tr);
}
}
i got in the below way.

gridView injection with api photos and onItem click listener

I'm using view injection like this. GridViews are created according to API data.
if(followup.size()>0)
{
for (Followup fData : followup)
{
String followupId= fData.get("id");
LinearLayout lLayout=(LinearLayout) findViewById(R.id.lLayout);
LinearLayout ll1= new LinearLayout(this);
ll1.setOrientation(LinearLayout.VERTICAL);
TextView txtfup= new TextView(this);
txtfup.setBackground(getResources().getDrawable(R.drawable.bg));
txtfup.setTypeface(face);
txtfup.setText(" Followup " + i++);
txtfup.setTextColor(Color.WHITE);
txtfup.setGravity(Gravity.LEFT);
txtfup.setTextSize(18);
LayoutParams params = new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT
);
txtfup.setLayoutParams(params);
ll1.addView(txtfup);
TextView txtEmpty= new TextView(this);
txtEmpty.setText("");
ll1.addView(txtEmpty);
lLayout.addView(ll1);
RelativeLayout rLayout=new RelativeLayout(this);
LinearLayout.LayoutParams relativeParams = new LinearLayout.LayoutParams(
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
relativeParams.setMargins(40, 8, 40, 30);// left, top, right, bottom
rLayout.setLayoutParams(relativeParams);
rLayout.requestLayout();
gridViewF= new GridView(this);
gridViewF.setHorizontalSpacing(10);
gridViewF.setNumColumns(5);
rLayout.addView(gridViewF);
lLayout.addView(rLayout);
//gridViewF.setOnItemClickListener(gridViewOnclickListener_followup);
//---------------------------------
RelativeLayout rLayout1=new RelativeLayout(this);
LinearLayout.LayoutParams relativeParams1 = new LinearLayout.LayoutParams(
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
relativeParams1.setMargins(40, 10, 40, 40);// left, top, right, bottom
rLayout1.setLayoutParams(relativeParams);
rLayout1.requestLayout();
TableRow row=new TableRow(this.getApplicationContext());
TableRow row1=new TableRow(this.getApplicationContext());
TableLayout tlayout=new TableLayout(this.getApplicationContext());
row=new TableRow(this);
row1=new TableRow(this);
TableLayout.LayoutParams tableRowParams=
new TableLayout.LayoutParams
(TableLayout.LayoutParams.FILL_PARENT,TableLayout.LayoutParams.WRAP_CONTENT);
tableRowParams.setMargins(6, 2, 6, 2);
row.setLayoutParams(tableRowParams);
row1.setLayoutParams(tableRowParams);
TextView text1=new TextView(this);
TextView text2=new TextView(this);
TextView text3=new TextView(this);
TextView text4=new TextView(this);
text1.setTypeface(face);
text2.setTypeface(face1);
text3.setTypeface(face);
text4.setTypeface(face1);
text1.setTextSize(18);
text2.setTextSize(16);
text3.setTextSize(18);
text4.setTextSize(16);
text1.setHeight(70);
text2.setHeight(70);
text3.setHeight(70);
text4.setHeight(70);
text1.setText("Description : ");
row.addView(text1);
text2.setText(fData.get("note"));
row.addView(text2);
text3.setText("Followup Date : ");
row1.addView(text3);
text4.setText(fData.get("followup_date"));
row1.addView(text4);
tlayout.addView(row);
tlayout.addView(row1);
rLayout1.addView(tlayout);
lLayout.addView(rLayout1);
//-----------------------------
photo= new ArrayList<Followup_Photos>();
for (Followup_Photos photos : followupPhoto) {
if(followupId.equalsIgnoreCase(photos.get("photo_type_id")))
photo.add(new Followup_Photos(photos.get("photo_id"), photos.get("photo_name"), photos.get("date_added"),
photos.get("photo_type_id")));
}
setGridView_Followup(photo);
Log.i(TAG, "followup photos"+ followupPhoto.toString());
Log.i(TAG, "photo array=>"+ photo.toString());
//------------------------------
LinearLayout ll4= new LinearLayout(this);
ll4.setOrientation(LinearLayout.HORIZONTAL);
TextView txtView= new TextView(this);
txtView.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
txtView.setHeight(30);
ll4.addView(txtView);
}
But there is a problem when I call gridViewF.setOnItemClickListener. Because more than one gridViews are created inside the loop but are the same name gridViewF. So, may I know any suggestion, please?
Steps
Get followup size (before the loop)
Make GridView array like GridView[] gridview = new GridView[size of followup];(Dont do it inside your for loop. Do it before it)
Use for loop using int i old pattern (for ease.. may be u have a better idea) and do gridview[i] = new GridView(Context)(Inside the loop)
Now set gridview[i].setonItemClickListener(------------------------);
Thanks a lot for your suggestion, MGDroid. I solved the issues. I changed my codes as you suggested and when I create gridview dynamically, I set id for each gridview. gridview[i].setId(i). And then inside gridView.setOnItemClickListener I get that id by parent.getId(). It worked fine. Here is my codes.
final int size= followup.size();
GridView[] gridview = new GridView[size];
fphotos= new ArrayList[size];
if(followup.size()>0)
{
for(i=0;i< size;i++)
{
fphotos[i]= new ArrayList<Followup_Photos>();
gridview[i]=new GridView(this);
gridview[i].setHorizontalSpacing(5);
gridview[i].setVerticalSpacing(15);
gridview[i].setNumColumns(5);
gridview[i].setId(i);
rLayout.addView(gridview[i]);
lLayout.addView(rLayout);
//gridview[i].setOnItemClickListener(FollowupGridListener);
gridview[i].setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
// TODO Auto-generated method stub
imageSelectedPosition = position;
int i= parent.getId();
Log.i(TAG, "selectedGrid id=>" + i);
for(int l=0;l<size;l++)
{
if(i==l)
initiatePopupImage_followup(imageSelectedPosition, fphotos[l]);
}
}
});
for (Followup_Photos photos : followupPhoto) {
if(followupId.equalsIgnoreCase(photos.get("photo_type_id")))
fphotos[i].add(new Followup_Photos(photos.get("photo_id"), photos.get("photo_name"), photos.get("date_added"),
photos.get("photo_type_id")));
}
setGridView_Followup(fphotos[i], gridview[i]);
}
//-------------------------------
private void initiatePopupImage_followup(int p, ArrayList<Followup_Photos> photos){
try{
// We need to get the instance of the LayoutInflater
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.image_layout_sever,(ViewGroup)findViewById(R.id.popup_element_sever));
pwindo = new PopupWindow(layout, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, true);
pwindo.setBackgroundDrawable(new BitmapDrawable()); //this one to affect setOutsideTouchable
pwindo.setOutsideTouchable(true); //To close when touch back button
pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
final ImageView myImage = (ImageView) layout.findViewById(R.id.imgView);
AsyncHttpClient client = new AsyncHttpClient();
String[] allowedContentTypes = new String[] { "image/png", "image/jpeg" , "image/gif" , "image/jpg"};
imageURL= photos.get(p).get("photo_name");
System.out.println("imageURL=>" + imageURL);
client.get(StaticHelper.AMAZON_BASE_URL + imageURL, new BinaryHttpResponseHandler(allowedContentTypes) {
#Override
public void onSuccess(byte[] fileData) {
Log.i("Image Download","Successful");
Bitmap bmp=BitmapFactory.decodeByteArray(fileData,0,fileData.length);
myImage.setImageBitmap(bmp);
myImage.setVisibility(View.VISIBLE);
}
});
}catch(Exception e){
e.printStackTrace();
}
}

How to declare n number of EditTexts dynamically in android?

I have an SQLite Database in my application with fieldname,fieldtype columns.
fieldname consists of EditText namimg ...ex: etsearch,etsave,etcancel etc..
fieldtype is EditText.
I add fieldname values dynamically. I need to declare these EditTexts in my java class, as i'am creating my layout using java code.
I created an arraylist and added the fieldname values into it. I am confused how to declare the EditTexts using for loop.
My code :
public class MainActivity extends Activity
{
LinearLayout ll;
LinearLayout llgrower;
Cursor cursor;
ArrayList<String> edittexts;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
ll = new LinearLayout(this);
llgrower= new LinearLayout(this);
ll.addView(llgrower);
this.setContentView(ll);
cursor = DataBase.getdata("query to get fieldname,fieldtype");
try
{
if (cursor.moveToFirst())
{
do
{
edittexts.add(cursor.getString(0));
} while (cursor.moveToNext());
}
}
catch (Exception e) {}
for (int i=0;i<edittexts.size();i++)
{
}
}
}
Here's the basics of how to do it.
LinearLayout layout = (LinearLayout) findViewById(R.id.layout); // this is whatever view you want to add them to
EditText editText;
for(int i=0;i<nunberOfEditTexts;i++){
editText = new EditText(this);
...
// set the properties of the EditText
...
// add to the view
layout.addView(editText);
}
You will probably want to look at LayoutParams to understand how to size and position your EditTexts.
Good luck
private void addEditText(int count) {
int id = 999;
EditText et;
RelativeLayout.LayoutParams params;
for(int i=0; i<count; i++) {
et= new EditText(this);
et.setId(id);
params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
params.setMargins(0, 10, 0, 0);
params.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
if(i > 0) {
params.addRule(RelativeLayout.BELOW, id - i);
}
//ASSIGN VALUE FOR YOUR EDITTEXT FROM db HERE.
layoutSpinnerContainer.addView(spinner, params);
id++;
}
}

How do I get values from a dynamically created android TableRow?

I used the code below to create a TableRow with content dynamically. It works good but I wish to get the values in the TableRow. Here is the sample code (I got it from Google), it has two text values in the TableRow. When I click the TableRow at any position it gives the corresponding value in the TableRow (I wish something similar to a ListView).
All_CustomsActivity.java
public class All_CustomsActivity extends Activity {
String companies[] = { "Google", "Windows", "iPhone", "Nokia", "Samsung",
"Google", "Windows", "iPhone", "Nokia", "Samsung", "Google",
"Windows", "iPhone", "Nokia", "Samsung" };
String os[] = { "Android", "Mango", "iOS", "Symbian", "Bada", "Android",
"Mango", "iOS", "Symbian", "Bada", "Android", "Mango", "iOS",
"Symbian", "Bada" };
TableLayout tl;
TableRow tr;
TableRow mTable = null;
TextView companyTV, valueTV;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tl = (TableLayout) findViewById(R.id.maintable);
// addHeaders();
addData();
}
/** This function add the headers to the table **/
public void addHeaders() {
/** Create a TableRow dynamically **/
tr = new TableRow(this);
tr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
/** Creating a TextView to add to the row **/
TextView companyTV = new TextView(this);
companyTV.setText("Companies");
companyTV.setTextColor(Color.GRAY);
companyTV.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
companyTV.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
companyTV.setPadding(5, 5, 5, 0);
tr.addView(companyTV); // Adding textView to tablerow.
/** Creating another textview **/
TextView valueTV = new TextView(this);
valueTV.setText("Operating Systems");
valueTV.setTextColor(Color.GRAY);
valueTV.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
valueTV.setPadding(5, 5, 5, 0);
valueTV.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
tr.addView(valueTV); // Adding textView to tablerow.
// Add the TableRow to the TableLayout
tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
// we are adding two textviews for the divider because we have two
// columns
tr = new TableRow(this);
tr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
/** Creating another textview **/
TextView divider = new TextView(this);
divider.setText("-----------------");
divider.setTextColor(Color.GREEN);
divider.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
divider.setPadding(5, 0, 0, 0);
divider.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
tr.addView(divider); // Adding textView to tablerow.
TextView divider2 = new TextView(this);
divider2.setText("-------------------------");
divider2.setTextColor(Color.GREEN);
divider2.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
divider2.setPadding(5, 0, 0, 0);
divider2.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
tr.addView(divider2); // Adding textView to tablerow.
// Add the TableRow to the TableLayout
tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
}
/** This function add the data to the table **/
public void addData() {
for (int i = 0; i < companies.length; i++) {
/** Create a TableRow dynamically **/
tr = new TableRow(this);
tr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
// ImageView im = new ImageView(this);
// im.setBackgroundResource(R.drawable.sample_image);
// im.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
// LayoutParams.WRAP_CONTENT));
// tr.addView(im);
/** Creating a TextView to add to the row **/
companyTV = new TextView(this);
companyTV.setText(companies[i]);
companyTV.setTextColor(Color.RED);
companyTV.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
companyTV.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
companyTV.setPadding(5, 5, 5, 5);
tr.addView(companyTV); // Adding textView to tablerow.
/** Creating another textview **/
valueTV = new TextView(this);
valueTV.setText(os[i]);
valueTV.setTextColor(Color.GREEN);
valueTV.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
valueTV.setPadding(5, 5, 5, 5);
valueTV.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
tr.addView(valueTV); // Adding textView to tablerow.
// Add the TableRow to the TableLayout
tl.addView(tr, new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
// tr.setOnClickListener(new View.OnClickListener() {
// public void onClick(View view) {
// view.setBackgroundColor(Color.DKGRAY);
// }
// });
//
// tr.setOnLongClickListener(new View.OnLongClickListener() {
// public boolean onLongClick(View v) {
// mTable = (TableRow) v; // assign selected TableRow gobally
// openContextMenu(v);
// return true;
// }
// });
}
}
// #Override
// public void onCreateContextMenu(ContextMenu menu, View v,
// ContextMenu.ContextMenuInfo menuInfo) {
// super.onCreateContextMenu(menu, v, menuInfo);
// menu.add(0, v.getId(), 0, "Do YourStuff");
//
// }
//
// #Override
// public boolean onContextItemSelected(MenuItem item) {
// int ccount = (mTable).getChildCount();
// String[] str = new String[ccount];
// for (int i = 0; i < ccount; i++) {
// TextView tv = (TextView) (((TableRow) mTable)).getChildAt(i);
// str[i] = tv.getText().toString(); // set selected text data into the
// // String array
// }
// Toast.makeText(All_CustomsActivity.this, Arrays.toString(str), 2)
// .show();
// return true;
// }
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinearLayout01"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbars="none" >
<TableLayout
android:id="#+id/maintable"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="0,1" >
</TableLayout>
</ScrollView>
</LinearLayout>
In the code above some lines are commented, these lines are what I already tried to get the row values but it failed. Can anyone help me with this?
I guess you're talking about getting those values on a TableRow click. If this is the case you could add a listener to your TableRow and use getChildAt to get a hold of the two TextViews and get the data:
//...
tr.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
TableRow t = (TableRow) view;
TextView firstTextView = (TextView) t.getChildAt(0);
TextView secondTextView = (TextView) t.getChildAt(1);
String firstText = firstTextView.getText().toString();
String secondText = secondTextView.getText().toString();
}
});
//...
To get data from textview first u need to identify its parent from that u need to get your textView child position then u can get data from it... Here is a sample
String myText;
((TextView) findViewById(R.id.tv)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TableRow tablerow = (TableRow)v.getParent();
TextView items = (TextView) tablerow.getChildAt(2);
myText = items.getText().toString();
}
});
spinnerSelection.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
TableRow selectedRow = (TableRow)spinnerSelection.getParent();
int index = tableLayout.indexOfChild(selectedRow);
Here index is the selected row index value and you can call all the views under the parent row (selectedRow) like the below set of lines.
Button roomNo = (Button) selectedRow.getChildAt(0);
Spinner selectionA = (Spinner) selectedRow.getChildAt(1);
Spinner selectionB = (Spinner) selectedRow.getChildAt(2);
Happy Coding!!

Categories

Resources