Dos botones de widgets de Android que llaman a la misma actividad con diferentes intenciones
Tengo un homescreenwidget en Android con dos botones. Ambos botones deben llamar a la misma actividad (clase), simplemente utilice una intención diferente, además de los extras de intención, para saber qué botón llamó a la clase. Por ahora sólo button1 está trabajando y llamando a la actividad. También recibo el valor clave en la actividad llamada.
¿Cómo puedo hacer que el segundo botón funcione? Aquí está mi código:
- Diferencia entre el tipo de entrada de texto sin formato y el tipo de entrada Person Name en Editext en android
- Cómo agregar un widget en el emulador de Android 4.2?
- ¿Cómo detener el desplazamiento en un Widget de Galería?
- ¿Cómo crear un diálogo de alerta con un título de varias líneas?
- Implementar android: button = "@ drawable / checkbox" por programa
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { super.onUpdate(context, appWidgetManager, appWidgetIds); for ( int i =0; i<appWidgetIds.length ; i++){ int appWidgetId = appWidgetIds[i]; Intent intent2 = new Intent(context, Main.class); Intent intent1 = new Intent(context, Main.class); // Intent put extras Button 1 String bread1 = "secure"; Bundle basket1 = new Bundle(); basket1.putString("key", bread1); intent1.putExtras(basket1); // Intent put extras Button 2 String bread2 = "insecure"; Bundle basket2 = new Bundle(); basket2.putString("key", bread2); intent2.putExtras(basket2); PendingIntent pending1 = PendingIntent.getActivity(context,0,intent1, 0); PendingIntent pending2 = PendingIntent.getActivity(context, 0, intent2, 0); RemoteViews views1 = new RemoteViews(context.getPackageName(),R.layout.maina); RemoteViews views2 = new RemoteViews(context.getPackageName(),R.layout.maina); views1.setOnClickPendingIntent(R.id.button1, pending1); views2.setOnClickPendingIntent(R.id.button2, pending2); appWidgetManager.updateAppWidget(appWidgetId, views1); appWidgetManager.updateAppWidget(appWidgetId, views2);
Aquí está el maina.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:weightSum="1" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" android:id="@+id/tvWidget" android:textAppearance="?android:attr/textAppearanceLarge"></TextView> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:weightSum="1" android:orientation="horizontal"> <Button android:text="@string/button1" android:id="@+id/button1" android:layout_height="wrap_content" android:layout_width="wrap_content"></Button> <Button android:text="@string/button2" android:id="@+id/button2" android:layout_height="wrap_content" android:layout_width="wrap_content"></Button> </LinearLayout> </LinearLayout>
- ¿Alguna vez alguien ha intentado utilizar DialerFilter?
- Cómo actualizar dinámicamente un ListView en Android
- Android - Cuando se inicia la misma actividad desde el widget con diferentes extras, ¿cómo evitar que aparezca la misma instancia después de regresar del botón HOME?
- Cómo crear un botón de flecha estilo iOS en Android?
- Sobre cómo trabajar con Fragment en Android 2.1 actualizado
- Vertical DrawerLayout o SlidingPaneLayout
- No se puede reemplazar el estilo switchStyle y NumberPicker en Android
- Android: abra una nueva actividad en los clics de listview
@Arnold ha creado 2 PendingIntent que son ….
PendingIntent pending1 = PendingIntent.getActivity(context,0,intent1, 0); PendingIntent pending2 = PendingIntent.getActivity(context, 0, intent2, 0);
Donde PendingIntent.getActivity (Contexto contexto, int requestCode, Intención intención, banderas int) tiene 4 parámetros. Tienes que enviar diferentes " requestCode " para diferentes PendingIntents.
Su código debe ser ….
PendingIntent pending1 = PendingIntent.getActivity(context,0,intent1, PendingIntent.FLAG_UPDATE_CURRENT); PendingIntent pending2 = PendingIntent.getActivity(context, 1, intent2, PendingIntent.FLAG_UPDATE_CURRENT);
En la clase principal que necesita para crear este …
String value; @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub Bundle b=intent.getExtras(); try{ value=b.getString("key"); } catch (Exception e) { // TODO: handle exception } super.onReceive(context, intent); }
Con el código onUpdate ….
@Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // Get all ids ComponentName thisWidget = new ComponentName(context, main.class); int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget); for (int widgetId : allWidgetIds) { // Create some random data RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.main); // Register an onClickListener for 1st button Intent intent = new Intent(context, main.class); intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,allWidgetIds); intent.putExtra("key", "1st Button"); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); remoteViews.setOnClickPendingIntent(R.id.button1, pendingIntent); // Register an onClickListener for 2nd button............ Intent intent2 = new Intent(context, main.class); intent2.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); intent2.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,allWidgetIds); intent2.putExtra("key", "2nd Button"); PendingIntent pendingIntent2 = PendingIntent.getBroadcast(context, 1, intent2, PendingIntent.FLAG_UPDATE_CURRENT); remoteViews.setOnClickPendingIntent(R.id.button2, pendingIntent2); appWidgetManager.updateAppWidget(widgetId, remoteViews); } }
A continuación, puede comprobar si el valor = 1 º botón o valor = 2 º botón para saber qué botón se ha hecho clic. Debe funcionar … SI no funciona por favor avíseme cuál es el problema …
Tuve un problema similar con el uso de 2 botones en un widget. He establecido OnClickPendingIntents en ambos, distinguido por diferentes setExtra () las llamadas. Pero sólo se llamó la última intención, incluso cuando se hace clic en el primer botón. He encontrado 2 soluciones: – asignar diferentes acciones a ambos PendingIntents – en el segundo PendingEvent establecer el PendingEvent.FLAG_CANCEL_CURRENT flag
Estoy muy poco familiarizado con PendingEvents y Widgets, por lo que no puedo ver los pros y los contras y se adhieren a la primera solución.
Tal vez eso podría ayudarle con su problema, también.
En mi caso:
remoteViews.setOnClickPendingIntent(R.id.widget_head, touch_man(context));
RemoteViews.setOnClickPendingIntent (R.id.widget_head2, touch_woman (contexto));
public static PendingIntent touch_man(Context context) { Intent intent = new Intent(); intent.setAction("touch_man"); return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } public static PendingIntent touch_woman(Context context) { Intent intent = new Intent(); intent.setAction("touch_woman"); return PendingIntent.getBroadcast(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT); }
En AndroidManifest
<receiver android:name="Receiver" android:label="widgetBroadcastReceiver" > <intent-filter> <action android:name="touch_man" /> <action android:name="touch_woman"/> </intent-filter> <meta-data android:name="android.appwidget.provider" android:resource="@xml/demo_widget_provider" /> </receiver>
Esta funcionando.
Su widget solo tendrá una vista remota. Intente cambiar el final de su fragmento de código a:
RemoteViews remoteView = new RemoteViews(context.getPackageName(),R.layout.maina); remoteView.setOnClickPendingIntent(R.id.button1, pending1); remoteView.setOnClickPendingIntent(R.id.button2, pending2); appWidgetManager.updateAppWidget(appWidgetId, remoteView);
De no ser así, sería útil ver su diseño en R.layout.maina
.
- Obtener mensajes de WordPress en mi aplicación para Android
- Android: cómo instalar apk en el dispositivo, sin utilizar las herramientas sdk de Android