Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically adding a custom view to RemoteViews

Could any help me to do this? My code is like:

 public CustomClass extends View {

//uses ondraw() to do something

}

For displaying my custom view on the home screen I created a class to extend Broadcast Receiver:

public class customAppWidgetProvider extends BroadcastReceiver {

    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {
            RemoteViews views = new RemoteViews(context.getPackageName(),
                    R.layout.main);

           //Here I want to create my custom view class object and I want to add this view to linear layout in main.xml

              CustomClass object = new CustomClass(context) ;
              LinearLayout layout = new LinearLayout(context) ;
              layout.setLayoutParameters(new LayoutParameters(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
              layout.addView(object);

            views.addview(R.id.linearlayout, (ViewGroup) layout) ;
            views.setOnClickPendingIntent(R.id.analog_appwidget,
                    PendingIntent.getActivity(context, 0,
                        new Intent(context, AlarmClock.class),
                        PendingIntent.FLAG_CANCEL_CURRENT));

            int[] appWidgetIds = intent.getIntArrayExtra(
                    AppWidgetManager.EXTRA_APPWIDGET_IDS);

            AppWidgetManager gm = AppWidgetManager.getInstance(context);
            gm.updateAppWidget(appWidgetIds, views);
        }
    }
}

But adding ViewGroup to RemoteView reference is not working... The main.xml layout above contains only LinearLayout. I want to add a custom view object to it. But after running this nothing shows on screen...

Please help me to do this. Thanks in Advance.

like image 831
Naidu Avatar asked Feb 24 '23 17:02

Naidu


1 Answers

It's not possible to add a custom View to an app widget. See the "Creating the App Widget Layout" section of the App Widgets Dev Guide for what View types are allowed.

Android 3.0 adds support for some views to display collections. See the "Using App Widgets with Collections" section for details.

Otherwise, to dynamically add an allowed View to an App Widget, after inflating the RemoteViews and getting a reference to it, you can use its addView(View) method, or the addView(View) method on any of the View objects already in the RemoteViews.

like image 165
Programmer Bruce Avatar answered Mar 10 '23 02:03

Programmer Bruce