2011-03-25 29 views
4

任何帮助我这样做?我的代码是这样的:动态添加自定义视图到RemoteViews

public CustomClass extends View { 

//uses ondraw() to do something 

} 

,主屏幕上显示我的自定义视图我创建了一个类来扩展广播接收器:

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); 
     } 
    } 
} 

但添加ViewGroup到远程视窗参考无法工作...上面的main.xml布局只包含LinearLayout。我想为它添加一个自定义视图对象。但运行后,屏幕上没有任何显示...

请帮我这么做。提前致谢。

回答

7

无法将自定义View添加到应用程序窗口小部件。请参阅App Widgets Dev Guide的the "Creating the App Widget Layout" section,了解允许哪些类型的View

Android 3.0增加了对某些视图的支持以显示集合。有关详细信息,请参阅“使用应用程序窗口小部件和集合”部分。

否则,动态添加允许的View到应用的Widget,充气RemoteViews并获得对它的引用后,您可以使用它addView(View)方法,或addView(View)方法在任何View对象已经在RemoteViews的。

相关问题