EzDevInfo.com

widget interview questions

Top widget frequently asked interview questions

Is there an easy way to strike through text in an app widget?

I was wondering if there is an easy way to strike text within an app widget in Android. In a normal activity, it is pretty easy, using textview flags:

textView.setPaintFlags(textView.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);

But since in an app widget, I can use only remoteviews... I do not know if this is possible

Anyone know something about this?

Thanks!


Source: (StackOverflow)

Best practices for writing javascript widgets [closed]

I have a JS script (widget) which is added to other websites. Technically its similar to Google analytics. My question is: what are your advices for ensuring robustness, keeping the code from interfering with other code on the site, avoiding errors for users etc. In general, what should I know to write a professional grade widget.

Notes: I can't use any JS library such as jquery etc..


Source: (StackOverflow)

Advertisements

How to make the Facebook Like Box responsive?

I am using the Facebook like box code in my side bar by pasting the Facebook code into a text widget. My theme is responsive, and I'd like to get the like box to resize correctly. I found this tutorial but he says the way he is doing it, isn't "fully responsive" so I didn't know if there was a better way to do it.


Source: (StackOverflow)

How to implement expandable panels in Android?

Is there an easy way to create expandable/collapsible blocks like seen in official market app?

Screenshot of Market app, when you click on "More" button, the description section expands with animation:

enter image description here

I know of SlidingDrawer but it doesn't seem to be suited for stuff like this--it's supposed to be put in overlay, and doesn't support half-open states.

Update:

Here's my half-working solution. It's a custom widget that extends LinearLayout. It kind-of works, but doesn't handle edge cases well, like content height smaller than collapsedHeight parameter. I'm sure with enough staring, digging in code and experimenting the quirks could be fixed. Was hoping to avoid doing that, and save some time by using a ready-made official or 3rd party solution. Anyway, here it is, code:

package com.example.androidapp.widgets;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.widget.LinearLayout;

import com.example.androidapp.R;

public class ExpandablePanel extends LinearLayout {

    private final int mHandleId;
    private final int mContentId;

    private View mHandle;
    private View mContent;

    private boolean mExpanded = true;
    private int mCollapsedHeight = 0;
    private int mContentHeight = 0;

    public ExpandablePanel(Context context) {
        this(context, null);
    }

    public ExpandablePanel(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray a = context.obtainStyledAttributes(attrs,
            R.styleable.ExpandablePanel, 0, 0);

        // How high the content should be in "collapsed" state
        mCollapsedHeight = (int) a.getDimension(
            R.styleable.ExpandablePanel_collapsedHeight, 0.0f);

        int handleId = a.getResourceId(R.styleable.ExpandablePanel_handle, 0);
        if (handleId == 0) {
            throw new IllegalArgumentException(
                "The handle attribute is required and must refer "
                    + "to a valid child.");
        }

        int contentId = a.getResourceId(R.styleable.ExpandablePanel_content, 0);
        if (contentId == 0) {
            throw new IllegalArgumentException(
                "The content attribute is required and must refer "
                    + "to a valid child.");
        }

        mHandleId = handleId;
        mContentId = contentId;

        a.recycle();
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        mHandle = findViewById(mHandleId);
        if (mHandle == null) {
            throw new IllegalArgumentException(
                "The handle attribute is must refer to an"
                    + " existing child.");
        }

        mContent = findViewById(mContentId);
        if (mContent == null) {
            throw new IllegalArgumentException(
                "The content attribute is must refer to an"
                    + " existing child.");
        }

        mHandle.setOnClickListener(new PanelToggler());
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (mContentHeight == 0) {
            // First, measure how high content wants to be
            mContent.measure(widthMeasureSpec, MeasureSpec.UNSPECIFIED);
            mContentHeight = mContent.getMeasuredHeight();
        }

        // Then let the usual thing happen
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    private class PanelToggler implements OnClickListener {
        public void onClick(View v) {
            Animation a;
            if (mExpanded) {
                a = new ExpandAnimation(mContentHeight, mCollapsedHeight);
            } else {
                a = new ExpandAnimation(mCollapsedHeight, mContentHeight);
            }
            a.setDuration(500);
            mContent.startAnimation(a);
            mExpanded = !mExpanded;
        }
    }

    private class ExpandAnimation extends Animation {
        private final int mStartHeight;
        private final int mDeltaHeight;

        public ExpandAnimation(int startHeight, int endHeight) {
            mStartHeight = startHeight;
            mDeltaHeight = endHeight - startHeight;
        }

        @Override
        protected void applyTransformation(float interpolatedTime,
            Transformation t) {
            android.view.ViewGroup.LayoutParams lp = mContent.getLayoutParams();
            lp.height = (int) (mStartHeight + mDeltaHeight * interpolatedTime);
            mContent.setLayoutParams(lp);
        }

        @Override
        public boolean willChangeBounds() {
            // TODO Auto-generated method stub
            return true;
        }
    }
}

Here's res/values/attrs.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <declare-styleable name="ExpandablePanel">
    <attr name="handle" format="reference" />
    <attr name="content" format="reference" />
    <attr name="collapsedHeight" format="dimension" />
  </declare-styleable>
</resources>

And here's how I use it in layout:

<com.example.androidapp.widgets.ExpandablePanel
    android:orientation="vertical"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    example:handle="@+id/expand"
    example:content="@+id/value"
    example:collapsedHeight="50dip">
    <TextView
        android:id="@id/value"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:maxHeight="50dip"
        />
    <Button
        android:id="@id/expand"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="More" />
</com.example.androidapp.widgets.ExpandablePanel>

Source: (StackOverflow)

How to build a Simple Android Widget

So I have a bit of experience building android applications. But now i would like to build a widget for android that would sit on the home screen and display a button, and when the button is pressed it plays a sound. I've been looking at tutorials online on how to set up an android widget but i cant seem to figure it out. Are there any good tutorials out there on how to make a standalone widget this simple or somewhere i can start? Thanks in advance, Peter


Source: (StackOverflow)

Fire jQuery event on div change

I have a div whose content may change in various ways: for instance its whole content may be reloaded via innerHTML, or nodes may be added via DOM methods. This in turn may happen via native javascript or indirectly via calls the jQuery API or via other libraries.

I want to execute some code when the content of the div changes, but I have absolutely no control on how it will change. Indeed I am designing a widget that may be used by other people, who are free to change the content of their divs the way they prefer. When the inner content of this div changes, the shape of the widget may have to be updated as well.

I'm using jQuery. Is there a way to capture the event that the content of this div has changed, however it happened?


Source: (StackOverflow)

How to embed Javascript widget that depends on jQuery into an unknown environment

I'm developing a javascript widget that depends on jQuery. The widget may or may not be loaded onto a page that already has jQuery loaded. There are many problems that come up in this case...

  1. If the web page does not have jQuery, I must load my own jQuery. There seems to be a delicate timing issue when doing this, however. For example, if my widget loads and executes before jQuery is finished loading and executing, I get a jQuery is not defined error.

  2. If the web page does have jQuery, I can usually work with it. If the jQuery version is old, however, I would like to load my own. If I do load my own, however, I need to do it in such a way as to not stomp on their $ variable. If I set jQuery.noConflict() and any of their scripts depend on $, then I have just broken their page.

  3. If the web page uses another javascript library (e.g. prototype), I needed to be sensitive of prototype's $ variable also.

Because of all of the above, it is seeming easier to not depend on jQuery. But before I go down that road, which will involve mostly rewriting my widget code, I wanted to ask for advice first.

The basic skeleton of my code, including the timing bug and sometimes $ bugs, follows:

<script type="text/javascript" charset="utf-8">
// <![CDATA
 if (typeof jQuery === 'undefined') {
  var head = document.getElementsByTagName('head')[0];
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = '{{ URL }}/jquery.js';
  head.appendChild(script);
 }
// ]]>
</script>
<script type="text/javascript" src="{{ URL }}/widget.js"></script>

My widget has the following structure:

(function($) {
 var mywidget = {
  init: function() {
   ...
  }
 };
 $(document).ready(function() {
   mywidget.init();
 });
})(jQuery);

If there are any pointers or resources for achieving a widget that can work in all the mentioned environments, they would be greatly appreciated.


Source: (StackOverflow)

how to add multiple widgets in one app?

I've just finished my Android widget. Now I need to have different sizes of this wiget for the user to choose from. for example I need a medium, small and large size widget. so when the user install the app and hold the the home screen then choose widget, in the widget menu I want him to see three widget with the same app name but with the size. something like this:

helloSmall helloMedium helloLarge

I have the medium one ready but how can I make the small and the large in the same app? knowing that all three sizes contain the same exact data and actions just the size and the background are different.

Thanks.


Source: (StackOverflow)

How do I change the background of an Android tab widget?

My class extends extends TabActivity

TabHost mTabHost =  getTabHost();

TabHost.TabSpec tab1 =mTabHost.newTabSpec("tab1");
TabHost.TabSpec tab2 =mTabHost.newTabSpec("tab2");

tab1 .setIndicator("title tab1");
tab2 .setIndicator("title tab2");
mTabHost.addTab(tab1);mTabHost.addTab(tab2);

TabHost.setCurrentTab(0 or 1)

Can anybody guide me how do I change the background image or color of selected tab?


Source: (StackOverflow)

google analytics - multiple trackers on one page (cookie conflict)

I'm writing a web application that's supposed to be embedded in other people's websites (kind of a widget). I'm using Google Analytics to track all the people that visit all instances of my script on the embedding websites. The problem is that I don't know how to use it so that it doesn't interfere with those websites' own Google Analytics accounts. I'm storing the tracker variable in a namespace, so I thought that should do it, but I haven't realized that GA stores its settings in cookies (__utma, __utmz etc.), and those cookies are used by both trackers, if there are two of them on the same page... So for example if I use _setVar to store some kind of user-defined variable in Google Analytics, and the embedding site does the same, we overwrite each other's values...

Of course it would be easiest if Google provided a way to change the name of the cookies to a custom one, but I can't find any way to do it. I thought about using cookie domain or path to force a separate cookie, but this doesn't work, because if I set domain or path to something other than the real domain/path, then the cookie is not readable for the page after reload...

Does anyone know a way to have two trackers on one page and make them use separate cookies so that they don't overwrite each other's settings?

Or, if that's completely impossible - is there any other analytics service with similar functionality as GA in which this is possible? (it would have to have advanced features like event and campaign tracking...)


Source: (StackOverflow)

Mulitple Instances of Pending Intent

I created a widget that when clicked activates a PendingIntent. The problem is when I have more than one widget on the screen only the latest one will start the PendingIntent.

I have read some about a unique request code, but not figured this out.

Any ideas how I can have multiple widgets and the PendingIntents work for each?

Here is a snippet of my code:

Intent openApp = new Intent(context, RunningTally.class);
    openApp.putExtra("widgetId", appWidgetId);
    PendingIntent pendingAppIntent = 
        PendingIntent.getActivity(context, 0, openApp, PendingIntent.FLAG_CANCEL_CURRENT  );
    views.setOnClickPendingIntent(R.id.openFull, pendingAppIntent);

Source: (StackOverflow)

Failed Binder transaction

Can anybody tell me the reason for failed binder transaction error? I can see this error message in logcat. I am getting this error while trying to put an bitmap dynamically in a widget...


Source: (StackOverflow)

QVision Widget Error upon compile

Only one error to go until I get to use this for my research!

Warning: Z-order assignment: " is not a valid widget.
FILE: qvvideoreaderblockwidget.ui

There's no line number that came with it. I tried finding but, failed to see an open-ended part.

What should I do to correctly compile this library?


Source: (StackOverflow)

Resizing an iframe based on content

I am working on an iGoogle-like application. Content from other applications (on other domains) is shown using iframes.

How do I resize the iframes to fit the height of the iframes' content?

I've tried to decipher the javascript Google uses but it's obfuscated, and searching the web has been fruitless so far.

Update: Please note that content is loaded from other domains, so the same-origin policy applies.


Source: (StackOverflow)

Widget for turning on/off camera flashlight in android

I am developing a widget for turning on/off camera led of phone.

I have made a widget that can work like toggle button (on/off).

Behavior is like follows : Sometimes the led light remains on when i enable the widget. But it doesnot turn on/off the camera led but it changes the icon.

I am not able to figure out whats the actual problem.

The same thing works fine in Activity (Torch Light Application).

Can anyone please explain me how can i solve my problem ?

Where i am going wrong ?

You can look at the code below that i have done so far

onUpdate method

@Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
            int[] appWidgetIds) {

         //super.onUpdate(context, appWidgetManager, appWidgetIds);

        remoteViews = new RemoteViews( context.getPackageName(), R.layout.widgetlayout);
        watchWidget = new ComponentName( context, FlashLightWidget.class );

        Intent intentClick = new Intent(context,FlashLightWidget.class);
        intentClick.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, ""+appWidgetIds[0]);

        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, appWidgetIds[0],intentClick, 0);
        remoteViews.setOnClickPendingIntent(R.id.myToggleWidget, pendingIntent);
        appWidgetManager.updateAppWidget( watchWidget, remoteViews );
        ctx=context;      
    }

onReceive method is as follows :

@Override

    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

        remoteViews = new RemoteViews( context.getPackageName(), R.layout.widgetlayout);
        if (intent.getAction()==null) {
            Bundle extras = intent.getExtras();
            if(extras!=null) {
                 if(status)
                    {
                        status=false;
                        remoteViews.setImageViewResource(R.id.myToggleWidget, R.drawable.shutdown1);
                        processOnClick();
                        Toast.makeText(context,"Status==false-onclick",Toast.LENGTH_SHORT).show();
                    }
                    else
                    {
                        status = true;
                        remoteViews.setImageViewResource(R.id.myToggleWidget, R.drawable.shutdown2);
                        processOffClick();
                        Toast.makeText(context,"Status==true--Ofclick",Toast.LENGTH_SHORT).show();
                    }
                }

                watchWidget = new ComponentName( context, FlashLightWidget.class );

                (AppWidgetManager.getInstance(context)).updateAppWidget( watchWidget, remoteViews );
           }
        }
  }

processOffClick method

private void processOffClick() {

        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.setPreviewCallback(null);
            mCamera.release();      
            mCamera = null;
        }
    }

processOnClick method

private void processOnClick() {

    if(mCamera==null)
    {
        try {
            mCamera = Camera.open();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    if (mCamera != null) {

        Parameters params = mCamera.getParameters();
        List<String> flashModes = params.getSupportedFlashModes();

        if (flashModes == null) {
            return;
        } else {

                params.setFlashMode(Parameters.FLASH_MODE_OFF);
                mCamera.setParameters(params);
                mCamera.startPreview();

            String flashMode = params.getFlashMode();

            if (!Parameters.FLASH_MODE_TORCH.equals(flashMode)) {

                if (flashModes.contains(Parameters.FLASH_MODE_TORCH)) {
                    params.setFlashMode(Parameters.FLASH_MODE_TORCH);
                    mCamera.setParameters(params);

                } 

            }
        }
    } else if (mCamera == null) {
        //Toast.makeText(ctx, "Camera not found", Toast.LENGTH_LONG).show();
        return;
    }
}

Source: (StackOverflow)