I tried checking if the height of the text in the textview is larger than the scroll view to handle situations where the user does not have to scroll to read the text but nothing online is working for me.
I tried solutions online but those don't work either
if (binding.wvTermsAndCond.getLocalVisibleRect(scrollBounds)) {
// imageView is within the visible window
Utils.showToast(mContext, "View is within the visible window", true);
} else {
// imageView is not within the visible window
Utils.showToast(mContext, "View is not within the visible window", true);
}
The not visible block was getting called
if you want to check if a view is visible or not you can use these methods:
public static boolean isVisible(final View view) {
if (view == null) {
return false;
}
if (!view.isShown()) {
return false;
}
final Rect actualPosition = new Rect();
view.getGlobalVisibleRect(actualPosition);
final Rect screen = new Rect(0, 0, getScreenWidth(), getScreenHeight());
return actualPosition.intersect(screen);
}
public static int getScreenWidth() {
return Resources.getSystem().getDisplayMetrics().widthPixels;
}
public static int getScreenHeight() {
return Resources.getSystem().getDisplayMetrics().heightPixels;
}
Related
I'm trying to avoid horizontal scrolling in ListView. The ListView instance holds list of HBox items, each item has a different width.
So far I'm using such a cell factory:
public class ListViewCell extends ListCell<Data>
{
#Override
public void updateItem(Data data, boolean empty)
{
super.updateItem(data, empty);
if(empty || data == null){
setGraphic(null);
setText(null);
}
if(data != null)
{
Region region = createRow(data);
region.prefWidthProperty().bind(mListView.widthProperty().subtract(20));
region.maxWidthProperty().bind(mListView.widthProperty().subtract(20));
setGraphic(region);
}
}
}
Unfortunately it is not enough. Usually after adding several items ListView's horizontal scrollbar appears. Even if it seems to be unnecessary.
How can I assure, that ListViewCell will not exceed it's parent width and horizontal scrollbar will not appear?
There is a lot at play here that make customizing ListView horizontal scrollbar behavior difficult to deal with. In addition to that, common misunderstandings on how ListView works can cause other problems.
The main issue to address is that the width of the ListCells will not automatically adapt when the vertical scrollbar becomes visible. Therefore, the moment it is, suddenly the contents are too wide to fit between the left edge of the ListView and the left edge of the vertical scrollbar, triggering a horizontal scrollbar. There is also the default padding of a ListCell as well as the border widths of the ListView itself to consider when determining the proper binding to set.
The following class that extends ListView:
public class WidthBoundList extends ListView {
private final BooleanProperty vbarVisibleProperty = new SimpleBooleanProperty(false);
private final boolean bindPrefWidth;
private final double scrollbarThickness;
private final double sumBorderSides;
public WidthBoundList(double scrollbarThickness, double sumBorderSides, boolean bindPrefWidth) {
this.scrollbarThickness = scrollbarThickness;
this.sumBorderSides = sumBorderSides;
this.bindPrefWidth = bindPrefWidth;
Platform.runLater(()->{
findScroller();
});
}
private void findScroller() {
if (!this.getChildren().isEmpty()) {
VirtualFlow flow = (VirtualFlow)this.getChildren().get(0);
if (flow != null) {
List<Node> flowChildren = flow.getChildrenUnmodifiable();
int len = flowChildren .size();
for (int i = 0; i < len; i++) {
Node n = flowChildren .get(i);
if (n.getClass().equals(VirtualScrollBar.class)) {
final ScrollBar bar = (ScrollBar) n;
if (bar.getOrientation().equals(Orientation.VERTICAL)) {
vbarVisibleProperty.bind(bar.visibleProperty());
bar.setPrefWidth(scrollbarThickness);
bar.setMinWidth(scrollbarThickness);
bar.setMaxWidth(scrollbarThickness);
} else if (bar.getOrientation().equals(Orientation.HORIZONTAL)) {
bar.setPrefHeight(scrollbarThickness);
bar.setMinHeight(scrollbarThickness);
bar.setMaxHeight(scrollbarThickness);
}
}
}
} else {
Platform.runLater(()->{
findScroller();
});
}
} else {
Platform.runLater(()->{
findScroller();
});
}
}
public void bindWidthScrollCondition(Region node) {
node.maxWidthProperty().unbind();
node.prefWidthProperty().unbind();
node.maxWidthProperty().bind(
Bindings.when(vbarVisibleProperty)
.then(this.widthProperty().subtract(scrollbarThickness).subtract(sumBorderSides))
.otherwise(this.widthProperty().subtract(sumBorderSides))
);
if (bindPrefWidth) {
node.prefWidthProperty().bind(node.maxWidthProperty());
}
}
}
Regarding your code, your bindings could cause problems. A ListCell's updateItem() method is not only called when the ListCell is created. A ListView can contain a pretty large list of data, so to improve the performance only the ListCells scrolled into view (and possibly a few before and after) need their graphic rendered. The updateItem() method handles this. In your code, a Region is being created over and over again and each and every one of them is being bound to the width of your ListView. Instead, the ListCell itself should be bound.
The following class extends ListCell and the method to bind the HBox is called in the constructor:
public class BoundListCell extends ListCell<String> {
private final HBox hbox;
private final Label label;
public BoundListCell(WidthBoundList widthBoundList) {
this.setPadding(Insets.EMPTY);
hbox = new HBox();
label = new Label();
hbox.setPadding(new Insets(2, 4, 2, 4));
hbox.getChildren().add(label);
widthBoundList.bindWidthScrollCondition(this);
}
#Override
public void updateItem(String data, boolean empty) {
super.updateItem(data, empty);
if (empty || data == null) {
label.setText("");
setGraphic(null);
setText(null);
} else {
label.setText(data);
setGraphic(hbox);
}
}
}
The scrollbarThickness parameter of WidthBoundList constructor has been set to 12. The sumBorderSides parameter has been set to 2 because my WidthBoundList has a one pixel border on the right and left. The bindPrefWidth parameter has been set to true to prevent the horizontal scroller from showing at all (labels have ellipses, any non-text nodes that you might add to the hbox will simply be clipped). Set bindPrefWidth to false to allow a horizontal scrollbar, and with these proper bindings it should only show when needed. An implementation:
private final WidthBoundList myListView = new WidthBoundList(12, 2, true);
public static void main(final String... a) {
Application.launch(a);
}
#Override
public void start(final Stage primaryStage) throws Exception {
myListView.setCellFactory(c -> new BoundListCell(myListView));
VBox vBox = new VBox();
vBox.setFillWidth(true);
vBox.setAlignment(Pos.CENTER);
vBox.setSpacing(5);
Button button = new Button("APPEND");
button.setOnAction((e)->{
myListView.getItems().add("THIS IS LIST ITEM NUMBER " + myListView.getItems().size());
});
vBox.getChildren().addAll(myListView, button);
myListView.maxWidthProperty().bind(vBox.widthProperty().subtract(20));
myListView.prefHeightProperty().bind(vBox.heightProperty().subtract(20));
primaryStage.setScene(new Scene(vBox, 200, 400));
primaryStage.show();
}
I need a vertical ViewPager in Android using Xamarin and the solution doesn't work. I searched some examples in java but there's an object developed by the git community that do all the work. Unfortunately there isn't in Xamarin. So, this is my code, it doesn't give me error, but it displays only a black screen. Nothing more.
I Extended the ViewPager class
public class VerticalViewPager : ViewPager {
public VerticalViewPager (Context context):base(context) {
Init ();
}
public VerticalViewPager(Context context, IAttributeSet attr):base(context, attr) {
Init();
}
public override bool OnTouchEvent (Android.Views.MotionEvent e) {
e.SetLocation (e.GetY (), e.GetX ());
return base.OnTouchEvent (e);
}
private void Init() {
SetPageTransformer (true, new PagerTransformer());
OverScrollMode = Android.Views.OverScrollMode.Never;
}
}
and create my PageTransformer
public class PagerTransformer : Java.Lang.Object, ViewPager.IPageTransformer {
int pageWidth;
int pageHeight;
float yPos;
public PagerTransformer () {}
public void TransformPage (View view, float position) {
pageWidth = view.Width;
pageHeight = view.Height;
if (position < -1) {
view.Alpha = 0;
}
else if (position <= 1) {
view.Alpha = 1;
// Counteract the default slide transition
view.TranslationX = (pageWidth * -position);
//set Y position to swipe in from top
yPos = position + pageHeight;
view.TranslationY = yPos;
}
else {
// This page is way off-screen to the right.
view.Alpha = 0;
}
}
}
In the MainActivity, onCreate method i set
page = FindViewById<VerticalViewPager> (Resource.Id.vertical_pager);
and obviously page is a VerticalViewPager object.
If I use a normale ViewPager, the app works fine. Any ideas about the reason of the black screen?
Any java code is appreciare as well!
Thanks
The reason of black screen is that you set your screen position out of visible bounds. Your visible bounds are from 0 to page height.
Try his : "yPos = position * pageHeight;" instead of "yPos = position + pageHeight;"
I have drawn a image on ONTOUCH with (X,Y)cordinates while moving the image it's cordinates should move along with the image when it reaches it end point the image should be drawn there or else the image should go back to it's starting position.
For eg:(in our mobile if kepad lock we will drag it to open if it reaches it end point the lock will open or else the image will reaches it's starting position).
Reffered link:http://www.vogella.com/tutorials/AndroidTouch/article.html
Here is my code:
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (mLocked) {
return false;
}
final int action = event.getAction();
float x = event.getX();
float y = event.getY();
if (mOnDrawerScrollListener != null) {
mOnDrawerScrollListener.onScrollStarted();
}
final int pt = getSide();
mTouchDelta = (int)(y - pt);
prepareTracking(pt);
mVelocityTracker.addMovement(event);
final Rect frame = mFrame;
final View handle = mHandle;
If anyone have idea about this please help me friends.
If you want to get(x, y) cordinates of view (ImageView), just use view.getX(), view.getY(). But when you get it in onCreate(), the results will be (0, 0), because it is not created yet. You should use view.getX(), view.getY() in onGlobalLayoutListener(). For e.g:
rlRoot.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
// TODO Auto-generated method stub
rlRoot.getViewTreeObserver().removeGlobalOnLayoutListener(this);
Log.d("X", view.getX()+"");
Log.d("Y", view.getY()+"");
}
});
With rlRoot is the layout includes your view and view may be ImageView or any View.
Try it, hope it help.
I am using this code, if anybody is familiar with it, its from the blackberry knowledge base. Anyway, I was wondering how to manipulate GIF's using this class. I can get the gif on the screen, but it keeps repeating and will not disappear. Any help is greatly appreciated!
public class AnimatedGIFField extends BitmapField
{
private GIFEncodedImage _image; //The image to draw.
private int _currentFrame; //The current frame in
the animation sequence.
private int _width; //The width of the image
(background frame).
private int _height; //The height of the image
(background frame).
private AnimatorThread _animatorThread;
public AnimatedGIFField(GIFEncodedImage image)
{
this(image, 0);
}
public AnimatedGIFField(GIFEncodedImage image, long style)
{
//Call super to setup the field with the specified style.
//The image is passed in as well for the field to
//configure its required size.
super(image.getBitmap(), style);
//Store the image and it's dimensions.
_image = image;
_width = image.getWidth();
_height = image.getHeight();
//Start the animation thread.
_animatorThread = new AnimatorThread(this);
_animatorThread.start();
}
protected void paint(Graphics graphics)
{
//Call super.paint. This will draw the first background
//frame and handle any required focus drawing.
super.paint(graphics);
//Don't redraw the background if this is the first frame.
if (_currentFrame != 0)
{
//Draw the animation frame.
graphics.drawImage(_image.getFrameLeft(_currentFrame), _image.getFrameTop(_currentFrame),
_image.getFrameWidth(_currentFrame), _image.getFrameHeight(_currentFrame), _image, _currentFrame, 0, 0);
}
}
//Stop the animation thread when the screen the field is on is
//popped off of the display stack.
protected void onUndisplay()
{
_animatorThread.stop();
super.onUndisplay();
}
//A thread to handle the animation.
private class AnimatorThread extends Thread
{
private AnimatedGIFField _theField;
private boolean _keepGoing = true;
private int _totalFrames; //The total number of
frames in the image.
private int _loopCount; //The number of times the
animation has looped (completed).
private int _totalLoops; //The number of times the animation should loop (set in the image).
public AnimatorThread(AnimatedGIFField theField)
{
_theField = theField;
_totalFrames = _image.getFrameCount();
_totalLoops = _image.getIterations();
}
public synchronized void stop()
{
_keepGoing = false;
}
public void run()
{
while(_keepGoing)
{
//Invalidate the field so that it is redrawn.
UiApplication.getUiApplication().invokeAndWait(new Runnable()
{
public void run()
{
_theField.invalidate();
}
});
try
{
//Sleep for the current frame delay before
//the next frame is drawn.
sleep(_image.getFrameDelay(_currentFrame) * 10);
}
catch (InterruptedException iex)
{} //Couldn't sleep.
//Increment the frame.
++_currentFrame;
if (_currentFrame == _totalFrames)
{
//Reset back to frame 0 if we have reached the end.
_currentFrame = 0;
++_loopCount;
//Check if the animation should continue.
if (_loopCount == _totalLoops)
{
_keepGoing = false;
}
}
}
}
}
}
Don't call super.paint(graphics), rather draw everything you need to draw by yourself. re-write your paint(Graphics graphics) method like below:
private boolean isPaint = true;
protected void paint(Graphics graphics) {
if(!isPaint) return;
// super.paint(graphics);
if (_currentFrame == _image.getFrameCount()-1) {
graphics.setGlobalAlpha(0);
isPaint = false;
}
graphics.drawImage(
_image.getFrameLeft(_currentFrame),
_image.getFrameTop(_currentFrame),
_image.getFrameWidth(_currentFrame),
_image.getFrameHeight(_currentFrame), _image,
_currentFrame, 0, 0
);
}
I'm rather new to programming Blackberries and was wondering if anybody knows of a tutorial or a snippet about how to load an image into the screen and set an onClick listener to it?
edit, got this far:
ButtonField btf1 = new ButtonField("Fine!");
ButtonField btf2 = new ButtonField("Great!");
RichTextField rtf = new RichTextField("HELLO, HOW ARE YOU?");
Bitmap LOGO = Bitmap.getBitmapResource("1.png");
BitmapField LogoBmpField = new BitmapField(LOGO);
HelloWorldScreen()
{
setTitle("My First App");
add(rtf);
add(btf1);
add(btf2);
add(LogoBmpField);
}
Thanks!
edit: by the way, how should interfaces be made for blackberry? simply by
ButtonField btf1 = new ButtonField("Fine!");
add(btf1);
Or is there some more visible way, such as in XML for android?
One more thing, how to I change or set properties of some object. Say I want to change the title of my button- btf1.(expecting list of available properties to appear ) doesn't give anything.
Place your image in your res folder and try this;
Bitmap bmpLogo = Bitmap.getBitmapResource("yourImage.jpg");
BitmapField logo = new BitmapField(bmpLogo){
protected boolean trackwheelClick(int status, int time)
{
// Your onclick code here
return true;
}
};
add(logo);
1) You need to make your BitmapField focusable.
I just tried this:
BitmapField LogoBmpField = new BitmapField(LOGO, BitmapField.FOCUSABLE) {
protected boolean trackwheelClick(int status, int time) {
System.out.println(" -- You clicked me! ");
return true;
}
};
and it seems to work.
2) And to change the text on your button use
setLabel()
btf1.setLabel("new button text");
public class MyScreen extends MainScreen {
public LanguageSelector() {
Bitmap logoBitmap = Bitmap.getBitmapResource("normalarabflag.png");
BitmapField LogoBmpField = new BitmapField(logoBitmap, BitmapField.FOCUSABLE | Field.FIELD_HCENTER) {
protected boolean navigationClick(int status, int time) {
System.out.println(" -- You clicked me! ");
UiApplication.getUiApplication().pushScreen(new SecoundScreen());
Dialog.alert("Load Complete");
return true;
}
};
LabelField labelfield = new LabelField("Arabic ",Field.FIELD_HCENTER|LabelField.FOCUSABLE);
VerticalFieldManager vrt=new VerticalFieldManager(USE_ALL_WIDTH) {
protected void sublayout(int maxWidth, int maxHeight) {
super.sublayout(Display.getWidth(),Display.getHeight());
setExtent(Display.getWidth(),Display.getHeight());
}
};
Font f=labelfield.getFont();
int hight1=f.getAdvance(labelfield.getText());
int k=labelfield.getPreferredHeight();
int number=hight1/Display.getWidth()+1;
int hight2=logoBitmap.getHeight();
int padding=(Display.getHeight()-((number*k)+hight2))/2;
if(padding>0) {
LogoBmpField.setPadding(padding,0,0,0);
}
vrt.add(LogoBmpField);
vrt.add(labelfield);
add(vrt);
}
}