2012-04-05 67 views
1

可能重复:
How to launch activity from android home screen widget我如何启动一个活动与家庭的Widget

请告诉我最简单的代码来启动从应用的主屏幕小部件的活动?

我到目前为止的代码不工作,没有在LogCat中显示.. ??

控件内有一个图像,当图像被点击时,应该启动应用程序。寻找一个片段。

public class MyWidget extends AppWidgetProvider 
{ 
    // Create an Intent to launch activity from ImageView 
    @Override 
    public void onEnabled(Context context) 
    { 
    Intent intent = new Intent(Intent.ACTION_MAIN, null); 
    intent.addCategory(Intent.CATEGORY_LAUNCHER); 

    ComponentName comp = new ComponentName(context.getPackageName(),MyWidget.class.getName()); 
    intent.setComponent(cn); 
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    PendingIntent myPI = PendingIntent.getActivity(context, 0, intent, 0); 

    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.content);//<-THE LAYOUT W/I THE MainActivity CLASS?? 

    views.setOnClickPendingIntent(R.id.widgetLauncher, myPI);//<-THE IMAGEVIEW ID?? 

    AppWidgetManager mgr = AppWidgetManager.getInstance(context); 
    mgr.updateAppWidget(comp, views); 
    } 
} 

控件布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" > 

    <ImageView 
     android:id="@+id/widgetLauncher" 
     android:layout_width="258dp" 
     android:layout_height="54dp" 
     android:layout_centerInParent="true" 
     android:src="@drawable/wgt_logo" > 
    </ImageView> 

</RelativeLayout> 
+0

http://buildmobile.com/how-to-code-an-android-widget – slayton 2012-04-05 17:15:23

+0

@Colin皮卡德一直在尝试各种方式,但没有。查看上面添加的代码 – CelticParser 2012-04-05 18:00:45

+0

什么是负号?我已经完成了研究,并且我无法得到任何工作。我添加了更多的代码。无论人们。 – CelticParser 2012-04-05 18:02:12

回答

4

这最后的工作:

public class MyWidget extends AppWidgetProvider 
{ 
    // Create an Intent to launch activity 
    @Override 
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,int[] appWidgetIds) 
    { 
    super.onUpdate(context, appWidgetManager, appWidgetIds); 

    RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.home_widget); 
    // When we click the widget, we want to open our main activity. 
    Intent launchActivity = new Intent(context, MainActivity.class); 
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, launchActivity, 0); 
    remoteViews.setOnClickPendingIntent(R.id.widget, pendingIntent);; 

    ComponentName thisWidget = new ComponentName(context, MyWidget.class); 
    AppWidgetManager manager = AppWidgetManager.getInstance(context); 
    manager.updateAppWidget(thisWidget, remoteViews); 
    } 
} 
+1

但是,这似乎为整个小部件设置了onclick,而不仅仅是图像?如何单击一个单独的事件来点击小部件并点击小部件中的图像? – Yusufk 2014-07-12 12:45:47

相关问题