Flex DataGrid Column Width - apache-flex

In my flex app I store the widths and visiblility of columns in an xml file. When the app loads it reads from the xml file and sets he columns values as applicable:
for(i = 0; i < columnsOrder.length; i++){
newOrder[i] = myDG.columns[Number(columnsOrder[i]) - 1];
newOrder[i].visible = (Number(columnsVisiblity[i]) == 1);
newOrder[i].width = Number(columnsWidth[i]);
}
myDG.columns = newOrder;
myDG.invalidateList();
The problem appears to be setting the visibility (it sets the visible field correctly but messes up the width)... I've tried setting it after setting the width (outside of the loop) and before the loop as well. It resizes the columns properly if I don't do anything with the visibility.
Any ideas?

Add an import statement at the top of your class file:
import mx.core.mx_internal;
Then remove using the mx_internal namespace, remove the owner of the column, change the width and then reasign the parent:
public static function resizeColumn(col:DataGridColumn, size:int):void
{
var owner:* = col.mx_internal::owner
col.mx_internal::owner = null;
col.width = size;
col.mx_internal::owner = owner;
}
This ought to do the trick (well, it did for us after a couple of days of swearing)

Is you horizontalScrollPolicy set to false on the datagrid?
"If the DataGrid's horizontalScrollPolicy property is false, all visible columns must fit in the displayable area, and the DataGrid will not always honor the width of the columns if the total width of the columns is too small or too large for the displayable area."
http://livedocs.adobe.com/flex/3/langref/mx/controls/dataGridClasses/DataGridColumn.html#width

I was able to get it to work by calling the above loop in a function twice... the first time it add the visible columns, the second time it sets the correct width. Not the best solution but I cannot spend any more time on it.

Related

TableColumn prefWidth

I have a TableView in my code for which I am saving the index and width of each TableColumn when the application shuts down (values are saved to a Properties file). When I start the application again, I want to reset the index and width of each TableColumns back to what is was when the application was shut down.
// If all columns are known, reorder the columns and set the width
if (allKnown) {
ObservableList<TableColumn<T, ?>> columns = FXCollections.observableArrayList();
// Column order and width
TableColumn<T, ?> column;
for (int i = 0; i < colIndex.length; i++) {
column = getOriginalColumns().get(colIndex[i]);
column.setPrefWidth(colWidths[i]);
columns.add(column);
}
getTableView().getColumns().setAll(columns);
}
getTableView().setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
Setting the index works correctly, the column is set in the correct location of the TableView. However, this does not work for the column's prefWidth (all columns are resizable). I have looked at different fora and the culprit seems to be the CONSTRAINED_RESIZE_POLICY. I want to keep that option, since the main screen of my application can be resized. If I use unconstrained, the width works, but then I loose the ability to auto-scale the TableView when the application's main window resizes.
Has anyone experienced the same and found a solution? Your help is greatly appreciated.
The only solution I have found is to initially set the minWidth instead of the prefWidth. then a few pulses after showing the UI, fix the minWidth so column resizing works normally again.

Set css from GWT (dynamically) to element with multiple styles associated

I have an instance of TabLayoutPanel where number of tabs would be set dynamically. Therefore to align tabs to fill whole width of the screen I need to
1) Override gwt-TabTayoutPanel default value width 16384px with auto !important (done);
2) Set width of gwt-TabTayoutPanelTab to proper percentage value (e.g. 2 tabs = 50%. 3 tabs = 33%, 4 tabs = 25% and so on).
I have a simple function for that which goes like this (simplified):
Double cssValue = 100.0/getWidgetCount();
(done)
3) Now here goes my question: how can i set the width of gwt-TabTayoutPanelTab from Java? I bolded Tabs because when i use this.getStyleName(); i got in return gwt-TabLayoutPanel not gwt-TabLayoutPanelTab .
In sum, I can divide my question in two:
-how to access TabLayoutPanelTab css class from GWT?;
-how to set said class width with my dynamically generated percentage number?;
EDIT:
Proper edit of function to determine percentage value.
-how to access TabLayoutPanelTab css class from GWT?;
int widgetCount = panel.getWidgetCount();
for(int i = 0; i < widgetCount; i++)
System.out.println(panel.getTabWidget(i).getParent().getStyleName());
}
As you can see there is no direct way to access the tabs. What you can do is access the widgets in the tabs, and get their parent, which is the tab in question.
-how to set said class width with my dynamically generated percentage number?;
If you have a certain amount off possible percentages then you can declare those classes (e.g. custom-Width-25, custom-width-33 etc.) where you specify the width with the !important annotation in order to override everything else.
If the previous solution is not acceptable then you can only use inline css. This means that the element must be already loaded in the DOM. Somewhere in your code where you know that the element is loaded you can call something like this :
int widgetCount = panel.getWidgetCount();
for(int i = 0; i < widgetCount; i++) {
com.google.gwt.user.client.Element tabElement = panel.getTabWidget(i).getParent().getElement();
tabElement.getStyle().setWidth(100/widgetCount, Unit.PCT);
}

Changing grid column's/row's width/height by storyboard animation in Windows Store App

I'm looking for some method to change grid column's width (or row's height) by animtion defined in Storyboard. I have already found some solutions for WPF apps, but they are all useless in case of Windows Store programming, eg.:
Grid Column changing Width when animating
how to change the height of a grid row in wpf using storyboard
http://www.codeproject.com/Articles/18379/WPF-Tutorial-Part-2-Writing-a-custom-animation-cla
Is such result obtainable by creating a custom class, inheriting from Timeline? If so, which components should be overrode for proper implementation?
You should be able to use a simple DoubleAnimation. Make sure to set EnableDependentAnimation=True, as outline here.
One thing to realize when trying things out is that ColumnDefinitions are a GridLength struct. You can find more information on them here. You will need to have the animation set the Value property.
Here is a sample method to animate a Grid ColumnDefinition MaxWidth.
private void Animate(ColumnDefinition column)
{
Storyboard storyboard = new Storyboard();
Duration duration = new Duration(TimeSpan.FromMilliseconds(500));
CubicEase ease = new CubicEase { EasingMode = EasingMode.EaseOut };
DoubleAnimation animation = new DoubleAnimation();
animation.EasingFunction = ease;
animation.Duration = duration;
storyboard.Children.Add(animation);
animation.From = 1000;
animation.To = 0;
animation.EnableDependentAnimation = true;
Storyboard.SetTarget(animation, column);
Storyboard.SetTargetProperty(animation, "(ColumnDefinition.MaxWidth)");
storyboard.Begin();
}

Flex 4, AdvancedDataGrid: initial column width

I got a problem with the widths of the advanceddatagrid-columns.
First of all, my layout is a HDividedBox, on the left there is the navigation, on the right there is a module, containing the advanceddatagrid.
left Side: navigation
right side: module (e.g. advanceddatagrid)
Most of the columns got a fixed width, some a minWidth. Now, initially the widths of the columns are correct.
So the problem is, whenever I load a new module and later reload the advanceddatagrid, the initial width of the columns is way different, although I change nothing in the process of loading the module. Neither the fixed widths nor the minWidths are initially correct.
I recently saw there is a solution for wrong widths of colums, it looks like that:
var oldPolicy:String = advanceddatagrid.myScrollPolicy;
advanceddatagrid.myScrollPolicy = ScrollPolicy.ON;
for(var i:int = 0; i < advanceddatagrid.columns.length; i++) {
var column:AdvancedDataGridColumn = advanceddatagrid.columns[i] as AdvancedDataGridColumn;
advanceddatagrid.column.width = column.width;
}
advanceddatagrid.validateNow();
advanceddatagrid.myScrollPolicy = oldPolicy;
advanceddatagrid.validateNow();
On the whole this is just a temporary change of the ScrollPolicy, re-setting the column-widths and then changing back. But still, it doenst work.
Does anyone have a clue?
Some relevant references that might help (the first one worked for me):
http://userflex.wordpress.com/2011/04/14/force-resize-datagrid/
http://forums.adobe.com/message/4285461
To summarize the first post (credit goes to Nick Schneble):
public function resizeColumns () : void
{
grid.validateNow ();
// forces the columns to size themselves properly
for each (var column : AdvancedDataGridColumn in grid.columns)
{
column.width = column.width;
}
}
It may seem a bit ridiculous, but if you execute this method whenever the underlying data in your data grid changes, you’ll have beautifully laid out columns.

Flex: Custom Item Renderer For Combobox controls truncates text

I've implemented a custom item renderer that I'm using with a combobox on a flex project I'm working on. It displays and icon and some text for each item. The only problem is that when the text is long the width of the menu is not being adjusted properly and the text is being truncated when displayed. I've tried tweaking all of the obvious properties to alleviate this problem but have not had any success. Does anyone know how to make the combobox menu width scale appropriately to whatever data it's rendering?
My custom item renderer implementation is:
<?xml version="1.0" encoding="utf-8"?>
<mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml"
styleName="plain" horizontalScrollPolicy="off">
<mx:Image source="{data.icon}" />
<mx:Label text="{data.label}" fontSize="11" fontWeight="bold" truncateToFit="false"/>
</mx:HBox>
And my combobox uses it like so:
<mx:ComboBox id="quicklinksMenu" change="quicklinkHandler(quicklinksMenu.selectedItem.data);" click="event.stopImmediatePropagation();" itemRenderer="renderers.QuickLinkItemRenderer" width="100%"/>
EDIT:
I should clarify on thing: I can set the dropdownWidth property on the combobox to some arbitrarily large value - this will make everything fit, but it will be too wide. Since the data being displayed in this combobox is generic, I want it to automatically size itself to the largest element in the dataprovider (the flex documentation says it will do this, but I have the feeling my custom item renderer is somehow breaking that behavior)
Just a random thought (no clue if this will help):
Try setting the parent HBox and the Label's widths to 100%. That's generally fixed any problems I've run into that were similar.
Have you tried using the calculatePreferredSizeFromData() method?
protected override function calculatePreferredSizeFromData(count:int):Object
This answer is probably too late, but I had a very similar problem with the DataGrid's column widths.
After much noodling, I decided to pre-render my text in a private TextField, get the width of the rendered text from that, and explicitly set the width of the column on all of the appropriate resize type events. A little hack-y but works well enough if you haven't got a lot of changing data.
You would need to do two things:
for the text, use mx.controls.Text (that supports text wrapping) instead of mx.controls.Label
set comboBox's dropdownFactory.variableRowHeight=true -- this dropdownFactory is normally a subclass of List, and the itemRenderer you are setting on ComboBox is what will be used to render each item in the list
And, do not explicitly set comboBox.dropdownWidth -- let the default value of comboBox.width be used as dropdown width.
If you look at the measure method of mx.controls.ComboBase, you'll see that the the comboBox calculates it's measuredMinWidth as a sum of the width of the text and the width of the comboBox button.
// Text fields have 4 pixels of white space added to each side
// by the player, so fudge this amount.
// If we don't have any data, measure a single space char for defaults
if (collection && collection.length > 0)
{
var prefSize:Object = calculatePreferredSizeFromData(collection.length);
var bm:EdgeMetrics = borderMetrics;
var textWidth:Number = prefSize.width + bm.left + bm.right + 8;
var textHeight:Number = prefSize.height + bm.top + bm.bottom
+ UITextField.TEXT_HEIGHT_PADDING;
measuredMinWidth = measuredWidth = textWidth + buttonWidth;
measuredMinHeight = measuredHeight = Math.max(textHeight, buttonHeight);
}
The calculatePreferredSizeFromData method mentioned by #defmeta (implemented in mx.controls.ComboBox) assumes that the data renderer is just a text field, and uses flash.text.lineMetrics to calculate the text width from label field in the data object. If you want to add an additional visual element to the item renderer and have the ComboBox take it's size into account when calculating it's own size, you will have to extend the mx.controls.ComboBox class and override the calculatePreferredSizeFromData method like so:
override protected function calculatePreferredSizeFromData(count:int):Object
{
var prefSize:Object = super.calculatePrefferedSizeFromData(count);
var maxW:Number = 0;
var maxH:Number = 0;
var bookmark:CursorBookmark = iterator ? iterator.bookmark : null;
var more:Boolean = iterator != null;
for ( var i:int = 0 ; i < count ; i++)
{
var data:Object;
if (more) data = iterator ? iterator.current : null;
else data = null;
if(data)
{
var imgH:Number;
var imgW:Number;
//calculate the image height and width using the data object here
maxH = Math.max(maxH, prefSize.height + imgH);
maxW = Math.max(maxW, prefSize.width + imgW);
}
if(iterator) iterator.moveNext();
}
if(iterator) iterator.seek(bookmark, 0);
return {width: maxW, height: maxH};
}
If possible store the image dimensions in the data object and use those values as imgH and imgW, that will make sizing much easier.
EDIT:
If you are adding elements to the render besides an image, like a label, you will also have to calculate their size as well when you iterate through the data elements and take those dimensions into account when calculating maxH and maxW.

Resources