how to find the view location in android - view

How can I find the view position in android?
To get the position I used view.getLeft(), view.getRight(), view.getTop() and view.getBottm(). But these methods are returning 0 (Zero). I used these methods after calling the setContentView() method.
If anyone know the code to get the view position, please help me.

This worked for me in 2.2:
custRegScrollView.smoothScrollTo(0, activity.findViewById(labelId)
.getTop() - (viewHeight / 2) + offset);
The bit of the code you're looking for is:
int viewPos = activity.findViewById(R.id.myView).getTop();
This should return the following spot in a view's "rectangle"
>______
| |
| |
|____|
I.e., the Y (vertical) coordinate of the top of the view.
Note that this is contextual based on what kind of Layout you're using. This was tested in a ScrollView, as seen above.
Hope this helps!

Where were you calling getLeft(), getTop(), etc? A view's position isn't set until onMeasure() is called, and so those methods will return 0 until then. onCreate() is called sometime before onMeasure(), and so calling getLeft() won't be much use in onCreate(). You may want to move your code to onMeasure() or onResume(). If you do override onMeasure(), however, be aware that it is usually called several times.

Related

UI XCTest, elements which exist in view

I am new to UI test writing.
I wanted to know if it is possible to know what elements are/exists in view. I want to know how many and how they are called.
I tried something like this to loop through all elements, but it does not work.
for element in app.accessibilityElements! {
print(element)
}
You're looking for the debugDescription method of XCUIElement, in your case to get the entire hierarchy of the current visible window:
app.debugDescription
Quoting header comments:
Provides debugging information about the element. The data in the string will vary based on the
time at which it is captured, but it may include any of the following as well as additional data:
• Values for the elements attributes.
• The entire tree of descendants rooted at the element.
• The element's query.
This data should be used for debugging only - depending on any of the data as part of a test is unsupported.
You could always have a break point in the testcase and then make some print calls to the console.
po app.accessibilityElements
po app.accessibilityElements.elementBoundByIndex(0)
po app.buttons["Icon Menu Light"]
etc.
And see what comes back in the output view hierarchy to reference, or just a simple call to po app will print the hierarchy.
Once you know a particular view exists.. app.buttons["Icon Menu Light"].exists.. you can then try using something like this to confirm the button/element is visible within the current view by passing it to a helper function like:
func isElementInView(element: XCUIElement) -> Bool {
let window = XCUIApplication().windows.elementBoundByIndex(0)
return CGRectContainsRect(window.frame, element.frame) }
This will tell you whether the element is visible on the screen, because the element.exist call will return true, even if the element is off screen and hasnt been shown to the user (i.e. if something hides off screen and then transitions into the frame)

How to avoid "special Case" when dealing with paging a UIScrollView with OrientationDidChange on app starting

So, to handle orientation changes (in a view, not a controller) we register with the UIDeviceOrientationDidChange notification. All good.
It gets called on app startup, reporting the correct dimensions but incorrectly saying something changed (due to having landscape views or other software-reasons this may be triggered).
After the few unnecessary messages, it will start sending legitimate messages. The device will report the correct "to" orientation, but it will still give the current frame (and bounds), which is invalid.
To scroll the page to the right, other SO questions lead me to remember to manually set the contentOffset, which has most of what I need. currentPage = current Y offset / width of scrollview. Basic math, cool.
That fixed most of my problems. For proper OO, I gave the scroll view a relayout function, which isn't quite the size of the iPad since it's a subview, and in it I do this:
float currentDeviceWidth = 768;
float currentHeight = 949; //logging the frame from portrait, landscape = 1024 w, 693 h
UIDeviceOrientation o = [[UIDevice currentDevice] orientation];
if (!UIDeviceOrientationIsPortrait(o)) {
//landscape
currentDeviceWidth = 1024;
currentHeight = 693;
}
else
NSLog(#"Moving to port, unless on startup, then its staying as");
Which handles the orientationDidChange: messages, but when the app starts, the scroll view is now smaller than it should be because it set its size as if the bounds it's getting are "about to change", when they're not.
Possible solutions:
a) [self performSelector:#selector(relayout) withObject:nil afterDelay:delayNum];
b) give a time delay before something like "BOOL dontIgnoreLayout" is set/unset
c) Find another way to test for orientation
d) manually go in and find out what's causing all the messages to be sent initially, remove all causes - this option is only possible if it's not created by the system on bootup. I can test this with a fresh project in a sec, though it's an enterprise app, may take some ripping if so.
Wondering if anyone solved this. If not, I have to put in "special case" or "time based" code, neither of which are OO style, at least not my preferred way (nor my coworkers).
If I missed something on SO, let me know, but as you can see, I have found a few answers thus far.
Thanks
I followed other people's examples by testing for Status Bar Orientation instead, it's seemingly always right, and shows conflicting messages with UIDevice currentOrientation... I know this has been found before, but the specific reason this fixed the problem is:
As per suggestions in other threads, I registered for notifications in ViewDidAppear and not viewDidLoad, this combination seems to be the win.

Big problems with MFC/WinAPI

I need to create a SDI form with a formview that has two tabs, which encapsulate multiple dialogs as the tab content. But the form has to have a colored background.
And things like these makes me hate programming.
First, I tried CTabControl, via resource editor, tried different things, but the undocumented behavior and the quirks with no answers led me into a roadblock.
After many hours of searching, I found that there is a control called property sheet, which is actually what I need.
Some more searching later, I found that property sheet can even be actually embedded onto CFormView like so: http://www.codeguru.com/Cpp/controls/propertysheet/article.php/c591
And that the dialog classes derived from CPropertyPage can be directly added as pages via AddPage method of CPropertySheet.
Great! Not quite so... Some of the controls didn't worked, and were not created, ran into weird asserts. Turns out the DS_CONTROL style was missing from the dialogs. Found it completely accidentaly on Link, no word about that on MSDN!!!! Property page must have: DS_3DLOOK | DS_CONTROL | WS_CHILD | WS_TABSTOP, and can have: DS_SHELLFONT | DS_LOCALEDIT | WS_CLIPCHILDREN styles! Not any other, which are created by default with resource editor. Sweet, super hidden information for software developers!
The quote in comments on that page: "OMG. That's where that behavior came from...
It turns out that the PlaySound API relied on that behavior when playing sounds on 64bit machines." by Larry Osterman, who as I understand works for Microsoft for 20 years, got me laughing out loud.
Anyway, fixed that, the dialog-controls(CPropertyPages) are created as expected now, and that part looks something remotely promising, but the next part with color is dead end again!
Normally you override WM_CTLCOLOR, check for control ID or hwnd and supply the necessary brush to set the color you need. Not quite so with CPropertySheet, the whole top row stays gray! For CTabCtrl it somehow works, for CPropertySheet it doesn't.
Why? Seems that the CPropertySheet is kinda embedded inside CTabControl or something, because if I override WM_ERASEBKGND, only the internal part changes the color.
Now it seems that there is a GetTabControl() method in the CPropertySheet, that returns the actual CTabCtrl* of the CPropertySheet. But since it's constructed internally, I can't find how to override it's WM_CTLCOLOR message processing.
There seems to be a way to subclass the windowproc, but after multiple tries I can't find any good source on how to do it. SubclassWindow doc on MSDN says: "The window must not already be attached to an MFC object when this function is called."?! What's that?
I tried creating a custom CCustomTabCtrl class based on CTabCtrl via MFC wizard, created an instance of it, called SubclassWindow from one of the CCustomPropertySheet handlers to override the internal CTabCtrl, but nothing works, mystical crashes deep inside MFC.
Tried setting WindowLong with GCL_HBRBACKGROUND for the internal CTabCtrl, nothing changed.
And worst of all, I can't find any sort of useful documentation or tutorials on the topic.
Most I can find is how to ownerdraw the tab control, but this is seriously wrong on so many ways, I want a standard control behavior minus background color, I don't want to support different color schemes, windows versions, IAccesible interfaces and all this stuff, and none of the ownerdraw samples I've seen can get even 10% of all the standard control behavior right. I have no illusion that I will create something better, I wont with the resources at hand.
I stumbled upon this thread, and I can't agree with the author more: http://arstechnica.com/civis/viewtopic.php?f=20&t=169886&sid=aad002424e80121e514548d428cf09c6 owner draw controls are undocumented PITA, that are impossible to do right, and there is NULL information on MSDN to help.
So is there anything I have missed or haven't tried yet? How to change the top strip background color of the CPropertySheet? Anyone?
Your only option is to ownerdraw the tab control. It's not that hard. Well, it is frustrating because MFC doesn't tell you how to make the necessary Win32 calls.
In your CPropertySheet-derived class, overwrite OnInitDialog() and add:
GetTabControl()->ModifyStyle(0,TCS_OWNERDRAWFIXED);
This puts your CPropertySheet-derived class in charge of drawing the tab control. Add a handler for WM_DRAWITEM (OnDrawItem) and change backgroundColor and textColor to match whatever colors you wanted. Code for OnDrawItem follows:
void CPropSht::OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct)
{
if (ODT_TAB != lpDrawItemStruct->CtlType)
{
CPropertySheet::OnDrawItem(nIDCtl, lpDrawItemStruct);
return;
}
// prepare to draw the tab control
COLORREF backgroundColor = RGB(0,255,0);
COLORREF textColor = RGB(0,0,255);
CTabCtrl *c_Tab = GetTabControl();
// Get the current tab item text.
TCHAR buffer[256] = {0};
TC_ITEM tcItem;
tcItem.pszText = buffer;
tcItem.cchTextMax = 256;
tcItem.mask = TCIF_TEXT;
if (!c_Tab->GetItem(c_Tab->GetCurSel(), &tcItem )) return;
// draw it
CDC aDC;
aDC.Attach(lpDrawItemStruct->hDC);
int nSavedDC = aDC.SaveDC();
CBrush newBrush;
newBrush.CreateSolidBrush(backgroundColor);
aDC.SelectObject(&newBrush);
aDC.FillRect(&lpDrawItemStruct->rcItem, &newBrush);
aDC.SetBkMode(TRANSPARENT);
aDC.SetTextColor(textColor);
aDC.DrawText(tcItem.pszText, &lpDrawItemStruct->rcItem, DT_CENTER|DT_VCENTER|DT_SINGLELINE);
aDC.RestoreDC(nSavedDC);
aDC.Detach();
}
Thank you for this solution but...
The above solution works well with one tab, but when you have multiple tabs it seems rename the wrong tabs. I needed to change the if statement for GetItem to:
if (!c_Tab->GetItem(lpDrawItemStruct->itemID, &tcItem )) return;
Needed lpDrawItemStruct->itemID to get the tabs named correctly

Getting Windows Phone 7 WebBrowser Component VerticalOffset

I want to persist the user's location in the document he or she is browsing, then bring them back to that spot when they return from tombstoning or between sessions.
My first approach was to wrap the browser component in a scrollviewer, but it turns out it handles its own scrolling and the scrollviewer never changes its verticaloffset.
My guess is that the browser component must have a scrollviewer or something like it embedded in it. I need to get the verticaloffset and scroll to an offset.
Any guesses how to get there?
My next approach would be a painful mish-mash of javascript and c# to figure out where they are...
Because of the way the WebBrowser control is built you'll need to track scrolling in Javascript then pass the location to managed code to handle storage of that value.
On resuming you'll need to have the managed code pass the scroll position to a Javascript function to reset the scroll position.
That's the theory but I haven't looked at the funcitonality around javascript scrolling events in the WebBrowser yet. That's the only place I can see possible problems.
Would be good to hear how you get on.
I've accepted Matt's answer, but I want to put in some details here. I'm also going to blog about how I did it once I'm completely done.
Since the WebBrowser component is essentially a black-box, you don't have as much control as I would like. Having said that, it is possible to get and set the vertical offset.
Javascript lets you ask for the value, but different browsers use different variations on HOW to ask. For THIS case I only have one browser to worry about.
First I make a couple of simple javascript functions:
function getVerticalOffset() {
return document.body.scrollTop;
}
function setVerticalOffset(offset) {
document.body.scrollTop = offset;
}
Next I call into the WebBrowser using the InvokeScript method on the browser object.
I'll post an update here with a link to my blog when I get the full write-up done.
I have been writing an eBook reader and had a similar question. Code for setting a scroll position has been easy enough to find.
Code for setting vertical scroll position:
string script = string.Format("window.scrollBy(0,{0});", "put your numeric value here");
wb_view.InvokeScript("eval", script);
Google didn't help much in finding solution for getting the value of current scroll position. Lacking any knowledge in javascript it took me almost two hours to get it right.
Code for getting the vertical scroll position:
var vScroll = wb_view.InvokeScript("eval",
"var vscroll = window.pageYOffset; vscroll.toString();");

Win32 List-View Control SubItem padding for custom-drawn SubItems?

When using custom-draw (NM_CUSTOMDRAW) to draw the entire contents of a ListView SubItem (in Report/Details view), it would be nice to be able to apply the same left and right
padding in my custom paint method that is applied by the control itself for non-custom-drawn items.
Is there a way to programmatically retrieve this padding value? Is it
related to the width of a particular character (" " or "w" or something?) or
is it a fixed value (6px on left and 3px on right or something) or...?
EDIT: To clarify, I want to add the same padding to my NM_CUSTOMDRAWn SubItems that the control adds to items that it draws, and the metric that I'm looking for, for example, is the white space between the beginning of the 2nd column and the word "Siamese" in the following screenshot (Note: screenshot from MSDN added to help explain my question):
(source: microsoft.com)
Note that the word "Siamese" is aligned with the header item ("Breed"). I would like to be able to guarantee the same alignment for custom-drawn items.
use ListView Header message HDM_GETBITMAPMARGIN
see link text
ListView_GetSubItemRect (LVM_GETSUBITEMTECT)
http://msdn.microsoft.com/en-us/library/ms930172.aspx
Despite what the documentation says I suspect LVIR_LABEL returns just the returns the bounding rectangle of the item text, as per ListView_GetItemRect.
(This just kept niggling me as I though I had actually seen an answer somewhere when playing with NM_CUSTOMDRAW).
Edit After Comment 2:
I imagine you have seen NMLVCUSTOMDRAW which if you are willing to use Version 6.0. has rcText. I wouldn't since I use Win2K.
Given what you have found I would go back to the suggestion of using
ListView_GetItemRect to get LVIR_LABEL and compare that with LVIR_BOUNDS and use the difference.
the way for doing this is retrieving the format of the corresponding column with
ListView_GetColumn()
then check the retrieved myLVCOLUMN.mask
LVCOLUMN myLVCOLUMN;
myLVCOLUMN.mask=LVCF_FMT;
ListView_GetColumn(hwnd,nCol,&myLVCOLUMN);
then when we draw the corresponding label belonging to that column
if(myLVCOLUMN.fmt & LVCFMT_CENTER)
DrawText(x,x,x,x, DT_CENTER | DT_WORD_ELLIPSIS );
else if (myLVCOLUMN.fmt & LVCFMT_RIGHT)
DrawText(x,x,x,x, DT_RIGHT | DT_WORD_ELLIPSIS );
else
DrawText(x,x,x,x, DT_LEFT | DT_WORD_ELLIPSIS );
I would assume that GetSystemMetrics() is that you need to look at. I think that SM_CXEDGE and SM_CYEDGE are probably the values you want, but don't quote me on that. ;-)
Can only guess without seeing your output.
A few suggestions: If you are using the DrawTextEx function, have you have experimented with DT_INTERNAL et al?
Are you accidentally putting in a blank image/icon.
Does it look ok in classic screen mode? If so I would look at XP Theme functions to see if some thing is going on.
Late edit after first comment:
I wonder if the size of rectangle matches the space required for the LVN_ENDLABELEDIT edit box around the text so the text doesn't move (or for a focus rectangle)?
I guess you could compare the result of LVM_GETITEMRECT with LVIR_LABEL on the first column and use the difference as your left border.

Resources