Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set Width dynamically of textview

Tags:

java

android

In my project, i need to draw rows of textview dynamically according to the data received to show it. To align them properly, i have used Table Row n xml, and called it in java code. Now, in their LayoutParam i have given MATCH_PARENT, but it wraps the text according to the length of data received. Now, i want to fix width of the fields for a tabular view. I do all this process in postExecute method. In this method, i used setWidth function to set it according to the width of header row element.Here, Sno is a view, while size is array containing width of all elements of headerRow.

 Sno.setTag(patient);
 Sno.setWidth(size[0]); 

But it didn't solve this problem, when i tried getWidth to see its width, it was showing its value 0. Then i tried to set this width using LinearLayout.LinearParams

LinearLayout.LayoutParams params_sno = new LinearLayout.LayoutParams(size[0],
LinearLayout.LayoutParams.MATCH_PARENT);
Sno.setLayoutParams(params_sno);

but still no benefit, secondaly, if i remove MATCH_PARENT from width of LayoutParams, its width got increased from width of header row element. fields without data are invisible.

like image 707
HimanshuR Avatar asked Sep 13 '13 12:09

HimanshuR


1 Answers

Try this

TableRow row = new TableRow(activityContext);

            TableLayout.LayoutParams td_tr = new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

            row.setWeightSum(10);
            row.setLayoutParams(td_tr);
            row.setGravity(Gravity.CENTER);
            row.setBackgroundColor(Color.parseColor("#D2D2D2"));

            TextView tv= new TextView(activityContext);
            tv.setText(String.valueOf(i));
            tv.setTextAppearance(activityContext, style.tvBoldRow);
            tv.setLayoutParams(new TableRow.LayoutParams(0 , LayoutParams.WRAP_CONTENT, 1)); // Here you can set weight to your TextView.
            tv.setPadding(2, 2, 2, 2);
            tv.setGravity(Gravity.CENTER);
            row.addView(tv);
like image 138
Sanket Shah Avatar answered Oct 22 '22 23:10

Sanket Shah