Search code examples
javaandroidandroid-widgetandroid-remoteview

How Do I getText().toString() a TextView Using RemoteViews?


I'm developing a widget for the first time, and remoteviews is a bit confusing compared to building an app.

I understand this part...

RemoteViews views = new Remoteviews(context.getPackageName(), R.layout.my_widget_layout);
views.setTextViewText(R.id.myTV, "Hello World");

Now the next is a bit complex for me. I want the button that I have on the widget to pass the TextView text and display it on a toast.

Here's what I started...

Intent myIntent = new Intent(context, myReceiver.class);
PendingIntent myPendingIntent = PendingIntent.getBroadcast(context, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.myButton, myPendingIntent);

My Class (This is where I need help!)

public static class myReceiver extends BroadcastReceiver{

Override
public void onReceive(Context context, Intent intent){
Toast.makeText(context, (HELP! I need to getText().toString() from the R.id.myTV), Toast.LENGTH_SHORT).show();
}
}

Thanks! Much appreciated!


Solution

  • You can add the text you want to display to the intent via putStringExtra method and then extract the extra string like this:

        @Override
        public void onReceive(Context context, Intent intent) {
            AppWidgetManager mgr = AppWidgetManager.getInstance(context);
            if (intent.getAction().equals(check-your-desired-action-here)) {
                String textThatYouWantToDisplay = intent.getStringExtra("name-of-the-desired-item");
                Toast.makeText(context,textThatYouWantToDisplay , Toast.LENGTH_SHORT).show();
            }
            super.onReceive(context, intent);
        }
    

    for more info:

    this sample widget app from google

    Build an app widget android document

    Intent getStringExtra method