Update TextView text size on AppWidget

北城以北 提交于 2020-01-11 11:33:13

问题


I can not figure this out, I've been struggling with it for days now, and I'm so tired of it..

I'm changing the text size of a TextView on an AppWidget with a Spinner from a Configuration Activity, and I can't get it to update correctly. It does not update the first time I tell it to, but it does update the second and third and every time afterwards.

I'll really really appreciate if someone would take a look at my code

Thank you very much

Config class:

public class WidgetConfig extends Activity implements OnItemSelectedListener{

    Dialog myDialog;
    Context context = WidgetConfig.this;
    static EditText info;
    static Spinner spinner;
    String appwidget_textsize = "0";
    private static final String[] paths = { "10", "12", "14", "16", "18", "20",
        "22", "24", "26", "28", "30", "32", "34", "36", "38", "40", "50", "60"};

    private static final String PREFS_NAME = "com.harteg.NotesWidgetPro.Widget";
    private static final String PREF_PREFIX_KEY = "prefix_";

    private static final String TAG = "MyActivity";

    int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;   

    float number;

    public WidgetConfig() {
        super();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        Log.v(TAG, "onCreate() started");

        setContentView(R.layout.widgetconfig);
        context = WidgetConfig.this;
        // back button = cancel
        setResult(RESULT_CANCELED);
        info = (EditText) findViewById(R.id.etwidgetconfig);

        findViewById(R.id.bwidgetconfig).setOnClickListener(mOnClickListener);
        findViewById(R.id.bwidgetconfig1).setOnClickListener(mOnClickListener);

        // Find the widget id from the intent.
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null) {
            mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);
        }
        // If they gave us an intent without the widget id, just bail.
        if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
            finish();
        }
        info.setText(loadTitlePref(WidgetConfig.this, mAppWidgetId));

        //------------ Text Size spinner ---------------
        spinner = (Spinner) findViewById(R.id.TxtSizeSP);


        ArrayAdapter<String> adapter = new ArrayAdapter<String>(WidgetConfig.this,
                android.R.layout.simple_spinner_item, paths);

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);

        spinner.setOnItemSelectedListener(this); 

        //--------------------------------------------------

    } // onCreate finished

    public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
        Log.v(TAG, "OnItemselected started");

        switch (position) {
        case 0:
            info.setTextSize(10.0f);
            Log.v(TAG, "position 0 chosed");
            appwidget_textsize = "10".toString();
            break;
        ... 

         }
         number = Float.valueOf(appwidget_textsize);    
        }


    public void onNothingSelected(AdapterView<?> arg0) {

    }

    View.OnClickListener mOnClickListener = new View.OnClickListener() {
        public void onClick(View v) {

            Log.v(TAG, "set remote view");
            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
            AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);

            Log.v(TAG, "set txt size");
            views.setFloat(R.id.tvConfigInput, "setTextSize", number);
            appWidgetManager.updateAppWidget(mAppWidgetId, views);
            Log.v(TAG, "over txt size");

            // When the button is clicked, save the string in our prefs and
            // return that they clicked OK.
            String titlePrefix = info.getText().toString();
            saveTitlePref(context, mAppWidgetId, titlePrefix);


            // Push widget update to surface with newly set prefix
            Widget.updateAppWidget(context, appWidgetManager, mAppWidgetId,
                    titlePrefix, views);

            // Make sure we pass back the original appWidgetId
            Intent resultValue = new Intent();
            resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                    mAppWidgetId);
            setResult(RESULT_OK, resultValue);
            Log.v(TAG, "onClick done");
            finish();

        }
    };

    // Write the prefix to the SharedPreferences object for this widget
    static void saveTitlePref(Context context, int mAppWidgetId, String text) {
        SharedPreferences.Editor editor = context.getSharedPreferences(PREFS_NAME, 0).edit();

        editor.putString(PREF_PREFIX_KEY + mAppWidgetId, text);

        // Saves the values
        editor.commit();
    }

    // Read the prefix from the SharedPreferences object for this widget.
    static String loadTitlePref(Context context, int mAppWidgetId) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE);

        String prefix = prefs.getString(PREF_PREFIX_KEY + mAppWidgetId, null);

        // If there is no preference saved, get the default from a resource
        if (prefix != null) {
            return prefix;
        } else {
            return context.getString(R.string.appwidget_prefix_default);
        }
    }

    static void deleteTitlePref(Context context, int mAppWidgetId) {
    }

    static void loadAllTitlePrefs(Context context,
            ArrayList<Integer> mAppWidgetIds, ArrayList<String> texts) {
    }

}

AppWidgetProvider class:

public class Widget extends AppWidgetProvider {

    private static final String TAG = "MyActivity";


    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
            int[] appWidgetIds) {

        Log.v(TAG, "onUpdate started");
        // TODO Auto-generated method stub
        //super.onUpdate(context, appWidgetManager, appWidgetIds);

        final int N = appWidgetIds.length;
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);

        for (int i=0; i<N; i++){
            int mAppWidgetId = appWidgetIds[i];
            String titlePrefix = WidgetConfig.loadTitlePref(context, mAppWidgetId);
                    updateAppWidget(context, appWidgetManager, mAppWidgetId, titlePrefix, views);

        }
    }

    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {

        final int N = appWidgetIds.length;
        for (int i=0; i<N; i++) {
            WidgetConfig.deleteTitlePref(context, appWidgetIds[i]);
        }
    }

    ...


    static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
            int mAppWidgetId, String titlePrefix, RemoteViews views) {
        Log.v(TAG, "updateAppWidget started");
        // Getting the string this way allows the string to be localized.  The format
        // string is filled in using java.util.Formatter-style format strings.
        CharSequence text = context.getString(R.string.appwidget_text_format,
              WidgetConfig.loadTitlePref(context, mAppWidgetId));        

        appWidgetManager = AppWidgetManager.getInstance(context); 

        ...

        views = new RemoteViews(context.getPackageName(), R.layout.widget);
        views.setTextViewText(R.id.tvConfigInput, text);

        // Tell the AppWidgetManager to perform an update on the current app widget
        Log.v(TAG, "Bottom update started");
        appWidgetManager.updateAppWidget(mAppWidgetId, views);

    }

}

Strings.xml

<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <string name="appwidget_prefix_default"></string>
    <string name="appwidget_textsize"></string>
    <string name="appwidget_text_format"><xliff:g id="prefix">%1$s</xliff:g></string> 
    ...   
</resources>

回答1:


So i finally got it working after trying a million different things. I ended up passing a string with the value via sharedpreferences, the same way i got the text to the widget, and just set views.setFloat(R.id.TextView, "setTextSize", Float.valueOf(SizeString)); in the widget provider it self.




回答2:


You have to broadcast ACTION_APPWIDGET_UPDATE yourself for the first time when a configuration Activity is launched.

The Appwidgets Documentation says :

The onUpdate() method will not be called when the App Widget is created (the system will not send the ACTION_APPWIDGET_UPDATE broadcast when a configuration Activity is launched). It is the responsibility of the configuration Activity to request an update from the AppWidgetManager when the App Widget is first created. However, onUpdate() will be called for subsequent updates—it is only skipped the first time.

Update:

Try by adding this code just above the finish() line of your Config activity.

AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
appWidgetManager.updateAppWidget(
        new ComponentName(this.getPackageName(), Widget.class.getName()), views);


来源:https://stackoverflow.com/questions/13483131/update-textview-text-size-on-appwidget

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!