【问题标题】:Set onClickListener to a button in widget [duplicate]将 onClickListener 设置为小部件中的按钮 [重复]
【发布时间】:2015-02-18 08:09:29
【问题描述】:

我有一个只有一个按钮的小部件。我读到 Listener 应该这样设置:

RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);

views.setOnClickPendingIntent(R.id.button1, pendingIntent);

但我有这个代码:

            try {
            sr = SpeechRecognizer
                    .createSpeechRecognizer(context);
            sr.setRecognitionListener(new MainActivity().new listener());

            Intent intent = new Intent(
                    RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
            intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                    RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
            intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
                    "voice.recognition.test");
            intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 5);
            sr.startListening(intent);

        } catch (Exception e) {
            Toast.makeText(context, "Exc: " + e, Toast.LENGTH_LONG).show();
        }

那应该是 onClick 事件.. 我不能让它成为一个待定的意图..

有什么想法吗? :)

【问题讨论】:

    标签: java android onclick widget


    【解决方案1】:

    您可以在您的小部件提供程序中处理PendingIntent

    以下是示例:

    1) 设置按钮点击的意图:

    final Intent intentButton = new Intent(context, MyWidgetProvider.class);
    
    intentButton.setAction(ACTION_MY_BUTTON);
    
    final PendingIntent pendingIntentButton =
            PendingIntent.getBroadcast(context, 0, intentButton, PendingIntent.FLAG_UPDATE_CURRENT);
    
    remoteViews.setOnClickPendingIntent(R.id.widgetButtonId, pendingIntentButton);
    

    2) 在MyWidgetProvider 中处理意图:

    @Override
    public void onReceive(final Context context, final Intent intent){
        super.onReceive(context, intent);
    
        final String action = intent.getAction();
    
        if (ACTION_MY_BUTTON.equals(action)) {
            // Do your stuff here!
        }
    

    【讨论】:

      猜你喜欢
      • 2019-11-07
      • 1970-01-01
      • 2020-02-22
      • 2018-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-06
      相关资源
      最近更新 更多