HorizontalScrollView.getMeasuredWidth() returns 0 - android

I am adding horizontalScrollView programatically , but when I try to do horizontalScrollView.getMeasuredWidth() it keeps returning 0.
void addCategory(String catTitle) {
mVideos = mShows.get(catTitle);
LinearLayout theLayout = (LinearLayout)findViewById(R.id.activitymain);
TextView textview=(TextView)getLayoutInflater().inflate(R.layout.categorytitle,null);
textview.setTextColor(Color.CYAN);
textview.setTextSize(20);
textview.setText(catTitle);
HorizontalScrollView horizontalScroll = new HorizontalScrollView (this,null);
LinearLayout LL = new LinearLayout(this);
LL.setOrientation(LinearLayout.HORIZONTAL);
LayoutParams LLParams = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
LL.setLayoutParams(LLParams);
HorizontalGalleryAdapter adapter = new HorizontalGalleryAdapter(this,mVideos);
for (int i = 0; i < adapter.getCount(); i++) {
View item = adapter.getView(i, null, null);
LL.addView(item);
}
horizontalScroll.addView(LL);
int maxScrollX = horizontalScroll.getChildAt(0).getMeasuredWidth()-horizontalScroll.getMeasuredWidth();
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Reset...");
String max= String.valueOf(maxScrollX);

Ok, I see the problem. You create a HorizontalScrollView, add a child to it, and then immediately try to get its measured width.
You cannot do this. You must add the horizontal scroll view to an existing already-drawn view in your activity first, because otherwise it doesn't have set dimensions yet.
Think about how would it know how many pixels WRAP_CONTENT will set the dimension to before its laid out in your view? If you add it to an existing, already-laid-out view in your activity, then that WRAP_CONTENT will actually get converted to some height.
It looks like you kind-of have a loop - horizontalScroll's dimensions depend on its content (WRAP_CONTENT), yet the content's (LinearLayout's) dimensions depend on the horizontalScroll's dimensions. This does not make sense. Perhaps try MATCH_PARENT for at least the width dimensions of your horizontal scroll view. Then, make sure to not look at dimensions until the view has been drawn.

Have a look into typical usage example for HorizontalScrollView:
// read a view's width
private int viewWidth(View view) {
view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
return view.getMeasuredWidth();
}
....
void getTableRowHeaderCellWidth(){
int tableAChildCount = ((TableRow)this.tableA.getChildAt(0)).getChildCount();
int tableBChildCount = ((TableRow)this.tableB.getChildAt(0)).getChildCount();;
for(int x=0; x<(tableAChildCount+tableBChildCount); x++){
if(x==0){
this.headerCellsWidth[x] = this.viewWidth(((TableRow)this.tableA.getChildAt(0)).getChildAt(x));
}else{
this.headerCellsWidth[x] = this.viewWidth(((TableRow)this.tableB.getChildAt(0)).getChildAt(x-1));
}
}
}
You can also check full details from this nice tutorial: The code of a Ninja.

Related

Scope of view.setId

I am populating a viewgroup using a for loop and assigning IDs based on the iteration of the for loop. Something like :
For(int i = 0; i<=listLength; i++){
ImageView iv = new Imageview(this);
RelativeLayout r = (RelativeLayout) findViewById(R.id.relativeLayout);
iv.setId(i);
iv.setImageResource(R.drawable.imageResource);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(10, 10);
if(i==0){
params.addRule(RelativeLayout.CENTER_IN_PARENT);
}
else{
params.addRule(RelativeLayout.ABOVE, i-1);
}
iv.setLayoutParams(params);
r.addView(iv);
}
However, when I try to place the next view relative to that ID, the view always appears in the top left corner of the parent view. The first view is in the right place but the others don't seem to know where the previous view is.
I think that it is because the scope of iv.setId(); is limited to that iteration of the for loop. Is that the reason?

Remove arbitrary gap between TableRow in TableLayout

I am using a TableLayout to print nine pictures. For some reason, I am getting a big gap between rows as shown in the image below. I set the background to green so the gaps are easy to see. My TableLayout is created programmatically. How do I fix this problem so that the gap between rows is not so big?
I have already tried tableRowParams.setMargins(0,0,0,0).
BTW: No I don't want to use ListView, etc.
I have been messing around with the code a lot trying to fix the problem. Below is simply the current state of the code:
EDIT: CORRECT IMAGE:
EDIT: the code now will work fine (thanks to #Guian):
public class FacialExpressionImagesTable extends TableLayout {
public FacialExpressionImagesTable(Context context, List<Bitmap> imageList, int sideDimension, int tableWidth, int tableHeight) {
super(context);
setLayoutParams(new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
setBackgroundColor(Color.BLUE);
setContent(imageList, context, sideDimension);
}
private void setContent(List<Bitmap> imageList, Context context, final int sideDimension) {
final int iHeight = imageList.get(0).getHeight();
final int iWidth = imageList.get(0).getWidth();
int ndx = 0;
for (int r = 0; r < sideDimension; r++) {
TableRow tableRow = new TableRow(context);
TableLayout.LayoutParams forRow = new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
tableRow.setLayoutParams(forRow);
tableRow.setBackgroundColor(Color.RED);
TableRow.LayoutParams elementLayout = new TableRow.LayoutParams(iWidth, LayoutParams.WRAP_CONTENT, 1);
tableRow.requestLayout();
for (int c = 0; c < sideDimension; c++) {
ImageView element = new ImageView(context);
element.setLayoutParams(elementLayout);
element.setAdjustViewBounds(true);
element.setPadding(0, 0, 3, 3);
element.setBackgroundColor(Color.GREEN);
element.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
element.setImageBitmap(imageList.get(ndx++));
element.requestLayout();
tableRow.addView(element);
}
addView(tableRow);
}
}
}
first : be aware that you exchange width and height in :
new TableRow.LayoutParams(iHeight, iWidth);
But anyway, you can't give your table itesm the size of the bitmap's getHeight and getWidth since they will be resized ( depending on the screen size, screen density etc ... you would have to compute the new size according to density... )
here I think they are reduced. that's why the height of the row is too big.
set your layout params so the element take wrap_content in height and 0dip with a layout_weight to 1 in width;
TableRow.LayoutParams elementLayout = new TableRow.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1 );
then the table row take wrap content as height :
TableLayout.LayoutParams forRow = new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
if image are not scaled as needed, you'll may have to set a scale type to your ImageViews : ( using setScaleType )
elementLayout.setScaleType(ScaleType.CENTER_INSIDE); // or
FIT_CENTER... not quite sure
It should be good, tell if its not.
hope that helps.
Also try setting padding to 0 so that there is no padding inside each row of your table

Is it possible to specify TableRow height?

I have a TableLayout with multiple TableRow views inside it. I wish to specify the height of the row programatically. E.g.
int rowHeight = calculateRowHeight();
TableLayout tableLayout = new TableLayout(activity);
TableRow tableRow = buildTableRow();
TableLayout.LayoutParams rowLp = new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT, rowHeight);
tableLayout.addView(tableRow, rowLp);
But this isn't working and is defaulting to WRAP_CONTENT. Digging around in the Android source code, I see this in TableLayout (triggered by the onMeasure() method):
private void findLargestCells(int widthMeasureSpec) {
final int count = getChildCount();
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child instanceof TableRow) {
final TableRow row = (TableRow) child;
// forces the row's height
final ViewGroup.LayoutParams layoutParams = row.getLayoutParams();
layoutParams.height = LayoutParams.WRAP_CONTENT;
Seems like any attempt to set the row height will be overridden by the TableLayout. Anyone know a way around this?
OK, I think I've got the hang of this now. The way to set the height of the row is not to fiddle with the TableLayout.LayoutParams attached to the TableRow, but the TableRow.LayoutParams attached to any of the cells. Simply make one cell the desired height and (assuming its the tallest cell) the entire row will be that height. In my case, I added an extra 1 pixel wide column set to the desired height which did the trick:
View spacerColumn = new View(activity);
//add the new column with a width of 1 pixel and the desired height
tableRow.addView(spacerColumn, new TableRow.LayoutParams(1, rowHeight));
First of all, You should convert it from dps to pixels using the display factor formula.
final float scale = getContext().getResources().getDisplayMetrics().density;
int trHeight = (int) (30 * scale + 0.5f);
int trWidth = (int) (67 * scale + 0.5f);
ViewGroup.LayoutParams layoutpParams = new ViewGroup.LayoutParams(trWidth, trHeight);
tableRow.setLayoutParams(layoutpParams);

Dynamic button display programmatically Android

I want to add buttons programmatically on the screen and I am getting the value by parsing an API and now I want to display the buttons according to the length of an array. I am doing this but I am only getting the last button displayed, but inside the for loop I'm getting all values correct but displaying only the last button. This is my code:
RelativeLayout relate;
//...
relate = (RelativeLayout)findViewById(R.id.relative);
protected void onPostExecute(Void result) {
if(dialog.isShowing() == true) {
dialog.dismiss();
}
//int width = 100, height =50, x = 10, y = 20;
for (int i =0;i<adapt_obj.city_name_array.length;i++){
b1 = new Button(myref);
b1.setText(adapt_obj.city_name_array[i]);
relate.addView(b1);
//relate.addView(b1, i, new RelativeLayout.LayoutParams(width,height));
//height = height+80;
}
listlocation.setAdapter(adapt_obj);
adapt_obj.notifyDataSetChanged();
}
A RelativeLayout will stack the views you add to it at the top-let corner if you don't specify some placement rules. Your buttons are added to the layout but they are placed one on top of each other and so the only visible is the last one you add. Here are some modification of your for loop:
RelativeLayout relate; relate = (RelativeLayout)findViewById(R.id.relative);
for (int i = 0; i < adapt_obj.city_name_array.length; i++){
Button b1 = new Button(myref);
b1.setId(100 + i);
b1.setText(adapt_obj.city_name_array[i]);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
if (i > 0) {
lp.addRule(RelativeLayout.BELOW, b1.getId() - 1);
}
b1.setLayoutParams(lp);
relate.addView(b1);
}
You mustn't give x and y values in Android.you can add buttom top left right of an item. Also layout parameters you should use wrap_content or fill_parent.
Button button = new Button(this);
button.setText(#"text");
button.setLayoutParams(new LayoutParams(WRAP_CONTENT,WRAP_CONTENT));
layout.addView(button);
I think the problem is with the relative layout. Your buttons might be getting stack on top of each other. Try making the parent a linear layout.

Android - ImageView margins not appearing in LinearLayout

Right now, I'm struggling to accomplish something as simple as adding margin space between my child ImageViews within a custom LinearLayout (modified RadioGroup that is designed to take in a custom ImageView that implements Checkable, didn't override onMesarue). Long story short, these images are of a fixed dimension (60x60dip), and since they are dynamic (from the web), I had to add them dynamically like so:
for(int i = 0; i < num; i++){
ImageViewRadioButton childImage = new ImageViewRadioButton(mContext);
float imagehWidthHeight = getResources().getDimension(R.dimen.image_width_and_height);
LinearLayout.LayoutParams imageParams = new LinearLayout.LayoutParams((int) imageWidthHeight, (int) imageWidthHeight);
int imageSpacing = Utils.dipsToPixels(10, mContext);
int innerPadding = Utils.dipsToPixels(5, mContext);
imageParams.leftMargin = imageSpacing;
imageParams.rightMargin = imageSpacing;
childImage.setAdjustViewBounds(true);
childImage.setLayoutParams(imageParams);
childImage.setBackgroundDrawable(getResources().getDrawable(R.drawable.blue_pressed));
childImage.setPadding(innerPadding, innerPadding, innerPadding, innerPadding);
childImage.setClickable(true);
//other non-image properties...
imageContainer.addView(childImage);
}
The only thing that does work is the padding, which it spaces it out properly. However, I am not seeing any space between the padding of each child (margins). Am I doing this correctly, or is there a better way of doing it short of overriding onMeasure to factor in each child's margins?
You had create imageParams but you are not using that parameters in your code instead of imageParams you are using swatchParams parameter. And you had not put a code of swatchParams parameter.

Categories

Resources