Categories
discuss

What does it mean to inflate a view from an xml file?

I am new to android development and keep coming across references to Inflating views from a layout xml file. I googled and searched the development guide but still wasn’t able to pick up a sense for what it means. If someone could provide a very simple example, it’d be much appreciated.

Answer

When you write an XML layout, it will be inflated by the Android OS which basically means that it will be rendered by creating view object in memory. Let’s call that implicit inflation (the OS will inflate the view for you). For instance:

class Name extends Activity{
    public void onCreate(){
         // the OS will inflate the your_layout.xml
         // file and use it for this activity
         setContentView(R.layout.your_layout);
    }
}

You can also inflate views explicitly by using the LayoutInflater. In that case you have to:

  1. Get an instance of the LayoutInflater
  2. Specify the XML to inflate
  3. Use the returned View
  4. Set the content view with returned view (above)

For instance:

LayoutInflater inflater = LayoutInflater.from(YourActivity.this); // 1
View theInflatedView = inflater.inflate(R.layout.your_layout, null); // 2 and 3
setContentView(theInflatedView) // 4
Categories
discuss

Calling an object method from an object property definition

I am trying to call an object method from an object (the same object) property definition to no avail.

var objectName = {
     method   :   function() {
          return "boop";
     },
     property :   this.method()
};

In this example I want to assign the return value of objectName.method (“boop”) to objectName.property.

I have tried objectName.method(), method(), window.objectName.method(), along with the bracket notation variants of all those as well, ex. this["method"], with no luck.

Answer

At initialization this does not refer to the object holding the property method (which is not yet initialized) but to the curent context – and since this has no method property you will get a TypeError.

If it is a custom getter you want, then you might look into using getters and setters in javascript – they are not supported by ECMAscript prior to ES5, but many engines support them nonetheless.

Categories
discuss

Embedding ListView inside Gallery

The goal is to implement a Gallery whose adapter returns ListViews (in other words, vertically scrolling ListViews embedded in a horizontally scrolling Gallery). It sort of works after a bit of work, but when attempting to scroll horizontally, the ListView looks very jittery, like there is some stickiness to it being centered. I have not observed this kind of behavior with any other type of View embedded in a Gallery.

Here is what I have tried:

Initially, I found that the ListView squashed touch events, so the gesture listener on the Gallery never gets fired.

So in the onCreate() method of the Activity, I created a GestureDetector:

galleryGestureDetector = new GestureDetector(this, gallery);

Then, inside the getView() method of the Gallery adapter, after the ListView has been inflated and configured, I have some code like this:

listView.setOnTouchListener(new OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {
        galleryGestureDetector.onTouchEvent(event);
        return true;
    }
});

In this case I have even gone to the extreme step of returning true from the OnTouchListener to ensure that the onTouchEvent() method of the listView is never actually called. The same jittery behavior occurs. As a result, I think I can rule out competing onTouchEvent() implementations between the two views.

I tried abusing the TouchDelegate concept as well by extending the Gallery’s touch rectangle to include the ListView and then forcing the ListView to delegate to it, but this was a futile effort as well.

I would throw up my hands and say it isn’t possible currently, but the Social Networking app that packs with the DroidX somehow accomplishes it!

Answer

The problem is that ListView is intercepting touch events from the Gallery and then altering the view position itself. This is what leads to the back and forth jittering effect that I see when I use the widgets as is. I consider this a bug in the Gallery widget, but in the meantime it can be fixed by subclassing Gallery like this:

public class BetterGallery extends Gallery {
private boolean scrollingHorizontally = false;

public BetterGallery(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

public BetterGallery(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public BetterGallery(Context context) {
    super(context);
}

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    super.onInterceptTouchEvent(ev);
    return scrollingHorizontally;
}

@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
    scrollingHorizontally = true;
    return super.onScroll(e1, e2, distanceX, distanceY);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    switch(event.getAction()) {
    case MotionEvent.ACTION_UP:
    case MotionEvent.ACTION_CANCEL:
        scrollingHorizontally = false;
    }

    return super.onTouchEvent(event);
}

}

If you use BetterGallery in place of Gallery, the whole thing works just fine!

Categories
discuss

Show Redirecting In.. CountDown Timer PHP

I have this code so far that redirects the user after 5 seconds to the correct URL:

<?php $url = $_GET['url']; header("refresh:5;url=$url"); include('ads.php'); ?>

Please could you tell me how i could display a countdown timer saying Redirecting In.. with .. being the amount of seconds left. I am new to web development so all code will be helpful!

Answer

<script type="text/javascript">

(function () {
    var timeLeft = 5,
        cinterval;

    var timeDec = function (){
        timeLeft--;
        document.getElementById('countdown').innerHTML = timeLeft;
        if(timeLeft === 0){
            clearInterval(cinterval);
        }
    };

    cinterval = setInterval(timeDec, 1000);
})();

</script>

Redirecting in <span id="countdown">5</span>.

You can try this.

Categories
discuss

check if a tree is a binary search tree

I have written the following code to check if a tree is a Binary search tree. Please help me check the code:

Okay! The code is edited now. This simple solution was suggested by someone in the posts below:

IsValidBST(root,-infinity,infinity);

bool IsValidBST(BinaryNode node, int MIN, int MAX) 
{
     if(node == null)
         return true;
     if(node.element > MIN 
         && node.element < MAX
         && IsValidBST(node.left,MIN,node.element)
         && IsValidBST(node.right,node.element,MAX))
         return true;
     else 
         return false;
}

Answer

A Method should only do one thing at a time. Also the way you do things are generally Weird. I will give you some almost-Java pseudocode. Sorry for that, but I have not touched Java for some Time. I hope it helps. Look at the comments I also did on the Question and I hope you sort it out!

Call your isBST like that :

public boolean isBst(BNode node)
{
    return isBinarySearchTree(node , Integer.MIN_VALUE , Integer.MIN_VALUE);
}

Internally :

public boolean isBinarySearchTree(BNode node , int min , int max)
{
    if(node.data < min || node.data > max)
        return false;
    //Check this node!
    //This algorithm doesn't recurse with null Arguments.
    //When a null is found the method returns true;
    //Look and you will find out.
    /*
     * Checking for Left SubTree
     */
    boolean leftIsBst = false;
    //If the Left Node Exists
    if(node.left != null)
    {
        //and the Left Data are Smaller than the Node Data
        if(node.left.data < node.data)
        {
            //Check if the subtree is Valid as well
            leftIsBst = isBinarySearchTree(node.left , min , node.data);
        }else
        {
            //Else if the Left data are Bigger return false;
            leftIsBst = false;
        }
    }else //if the Left Node Doesn't Exist return true;
    {
        leftIsBst = true;
    }

    /*
     * Checking for Right SubTree - Similar Logic
     */
    boolean rightIsBst = false;
    //If the Right Node Exists
    if(node.right != null)
    {
        //and the Right Data are Bigger (or Equal) than the Node Data
        if(node.right.data >= node.data)
        {
            //Check if the subtree is Valid as well
            rightIsBst = isBinarySearchTree(node.right , node.data+1 , max);
        }else
        {
            //Else if the Right data are Smaller return false;
            rightIsBst = false;
        }
    }else //if the Right Node Doesn't Exist return true;
    {
        rightIsBst = true;
    }

    //if both are true then this means that subtrees are BST too
    return (leftIsBst && rightIsBst);
}

Now : If you want to find the Min and Max Values of each Subtree you should use a Container (I used an ArrayList) and store a triplet of Node, Min, Max which represents the root node and the values (obviously).

eg.

/*
 * A Class which is used when getting subTrees Values
 */
class TreeValues
{
    BNode root; //Which node those values apply for
    int Min;
    int Max;
    TreeValues(BNode _node , _min , _max)
    {
        root = _node;
        Min = _min;
        Max = _max;
    }
}

And a :

/*
 * Use this as your container to store Min and Max of the whole
 */
ArrayList<TreeValues> myValues = new ArrayList<TreeValues>;

Now this is a method which finds the Min and Max values of a given node:

/*
 * Method Used to get Values for one Subtree
 * Returns a TreeValues Object containing that (sub-)trees values
 */ 
public TreeValues GetSubTreeValues(BNode node)
{
    //Keep information on the data of the Subtree's Startnode
    //We gonna need it later
    BNode SubtreeRoot = node;

    //The Min value of a BST Tree exists in the leftmost child
    //and the Max in the RightMost child

    int MinValue = 0;

    //If there is not a Left Child
    if(node.left == null)
    {
        //The Min Value is this node's data
        MinValue = node.data;
    }else
    {
        //Get me the Leftmost Child
        while(node.left != null)
        {
            node = node.left;
        }
        MinValue = node.data;
    }
    //Reset the node to original value
    node = SubtreeRoot; //Edit - fix
    //Similarly for the Right Child.
    if(node.right == null)
    {
        MaxValue = node.data;
    }else
    {
        int MaxValue = 0;
        //Similarly
        while(node.right != null)
        {
            node = node.right;
        }
        MaxValue = node.data;
    }
    //Return the info.
    return new TreeValues(SubtreeRoot , MinValue , MaxValue);   
}

But this returns Values for one Node only, So we gonna use this to find for the Whole Tree:

public void GetTreeValues(BNode node)
{
    //Add this node to the Container with Tree Data 
    myValues.add(GetSubTreeValues(node));

    //Get Left Child Values, if it exists ...
    if(node.left != null)
        GetTreeValues(node.left);
    //Similarly.
    if(node.right != null)
        GetTreeValues(node.right);
    //Nothing is returned, we put everything to the myValues container
    return; 
}

Using this methods, your call should look like

if(isBinarySearchTree(root))
    GetTreeValues(root);
//else ... Do Something

This is almost Java. It should work with some modification and fix. Find a good OO book, it will help you. Note, that this solution could be broke down into more methods.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..