【问题标题】:Android - create widget on home screenAndroid - 在主屏幕上创建小部件
【发布时间】:2013-03-04 05:03:58
【问题描述】:

我想从 url 加载图像,以及图像下方显示的文本。像这样,

  1. ImageView 和 TextView 上的对齐,这是我的代码,但没有显示所需的布局

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#00FFFF"
        android:padding="0.1dp">
    
    <TextView android:text="@string/widgetUrl"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="0.8"
    android:layout_gravity="center_vertical"
    android:textColor="#000000">
    </TextView>
    <TextView android:text="@string/widgetTitle"
    android:id="@+id/widgetTitle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="0.8"
    android:layout_gravity="center_vertical"
            android:layout_alignParentBottom="true"  
            android:layout_centerHorizontal="true"
    android:textColor="#ffffff">
    </TextView>
    <ImageView android:id="@+id/widgetBackground"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="0.5"
    android:src="@drawable/ic_launcher"
    android:layout_gravity="center_vertical">
    </ImageView>
    
    </LinearLayout>
    
  2. 如何从 web 加载图像并在 java 代码中显示在布局上?以下是我的小部件提供程序代码:

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
        int[] appWidgetIds) {
    super.onUpdate(context, appWidgetManager, appWidgetIds);
    
    Log.i(WIDGETTAG, "onUpdate");
    
    final int N = appWidgetIds.length;
    
    // Perform this loop procedure for each App Widget that belongs to this provider
    for (int i=0; i<N; i++) {
        int appWidgetId = appWidgetIds[i];
    
        Log.i(WIDGETTAG, "updating widget[id] " + appWidgetId);
    
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
    
        /* View setup */
        views.setInt(R.id.widgetTitle, "setBackgroundColor", Color.argb(150, 0, 0, 0));
    
        Intent intent = new Intent(context, ChopInkService.class);
        intent.setAction(ChopInkService.UPDATE_IMAGE);
        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
        PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
    
        views.setOnClickPendingIntent(R.id.widgetBackground, pendingIntent);
        Log.i(WIDGETTAG, "pending intent set");
    
        // Tell the AppWidgetManager to perform an update on the current App Widget
        appWidgetManager.updateAppWidget(appWidgetId, views);
    }
    
  3. Service 和 AppWidgetProvider 的工作是什么?

    • 从 url 加载图片是 service 还是 AppWidgetProvider 的工作?
    • 视图设置应该放在 service 或 AppWidgetProvider 中吗?
  4. 当用户点击小部件时,如何将用户重定向到 Play 商店?

提前致谢。我是新手,如果我问了一个愚蠢的问题,请道歉。

【问题讨论】:

    标签: android android-layout widget android-imageview


    【解决方案1】:

    可用的小部件视图和布局

    widget 受限于它可以使用的 View 类。作为布局,您可以使用 FrameLayout、LinearLayout 和 RelativeLayout 类。作为视图,您可以使用 AnalogClock、Button、Chromometer、ImageButton、ImageView、ProgressBar 和 TextView。

    从 Android 3.0 开始,可以使用更多视图:GridView、ListView、StackView、ViewFlipper 和 AdapterViewFlipper。此适配器视图要求您定义一个集合视图小部件,本教程稍后将对此进行介绍。 p>

    在 Widget 的视图上唯一可能的交互是通过 OnClickListener。这个 OnClickListener 可以注册在一个 widget 上,由用户触发。

    AppWidgetProvider

    您的 BroadcastReceiver 通常会扩展 AppWidgetProvider 类。

    AppWidgetProvider 类实现 onReceive() 方法,提取所需信息并调用以下小部件生命周期方法。

    由于您可以将小部件的多个实例添加到主屏幕,因此您有生命周期方法,这些方法仅在添加/删除到主屏幕的第一个实例时调用,而其他方法则为小部件的每个实例调用。

    Widget 的生命周期

    onEnabled() - 首次将小部件实例添加到主屏幕时调用

    onDisabled() - 在您的小部件的最后一个实例从主屏幕移除后调用。

    onUpdate() - 每次更新小部件时调用。包含需要更新的 appWidgetIds 的 ID。请注意,这可能是此提供程序的所有 AppWidget 实例,也可能只是其中的一个子集,如方法 JavaDoc 中所述。例如,如果将多个小部件添加到主屏幕,则只有最后一个会更改(直到重新安装)。

    onDeleted() - Widget 实例已从主屏幕移除

    这些方法中的所有长时间运行的操作都应该在服务中执行,因为广播接收器的执行时间是有限的。在 onReceive() 方法中使用异步处理没有帮助,因为系统可以在他的 onReceive() 方法之后终止广播进程。

    有关小部件的更多详细信息请查看How to create widget in Android?

    Tutorial1
    Tutorial2

    【讨论】:

    • 是 hu 回复 apu j 6u 但我认为网络问题 yar
    【解决方案2】:

    您好,您可以查看此 tutorial 以了解从 URL (Http) 加载图像。

    试试下面的代码:

    URL 图像小部件提供程序类

    public class URLImageAppWidgetProvider extends AppWidgetProvider {
        public static String TAG = "URLImageWidget";
    
        public static class Size_1_1 extends URLImageAppWidgetProvider {}
        public static class Size_1_2 extends URLImageAppWidgetProvider {}
        public static class Size_1_4 extends URLImageAppWidgetProvider {}
        public static class Size_2_2 extends URLImageAppWidgetProvider {}
    
        @Override
        public void onUpdate(Context context, AppWidgetManager appWidgetManager,
                        int[] appWidgetIds) {
                super.onUpdate(context, appWidgetManager, appWidgetIds);
    
                SharedPreferences urls = context.getSharedPreferences("urls.conf", Context.MODE_PRIVATE);
                for (int id : appWidgetIds) {
                        String url = urls.getString("url_" + id, "");
                        update(context, appWidgetManager, id, url);
                }       
    
        }
    
    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
        super.onDeleted(context, appWidgetIds);
    
        SharedPreferences urls = context.getSharedPreferences("urls.conf", Context.MODE_PRIVATE);
        SharedPreferences.Editor urls_editor = urls.edit();
                for (int id : appWidgetIds) {
                        urls_editor.remove("url_" + id);
                }
    
                urls_editor.commit();
    
    }
    
        public static void update(final Context context, final AppWidgetManager appWidgetManager, final int id, final String url) {
                new Thread() {
                        public void run() {
                                Bitmap img = getBitmapFromUrl(url);
                                if (img != null) {
                                        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.main);
                                        views.setImageViewBitmap(R.id.img, img);
                                        appWidgetManager.updateAppWidget(id, views);    
                                }
                        }
                }.start();
        }
    
    private static Bitmap getBitmapFromUrl(final String url) {
        try {
                return BitmapFactory.decodeStream(((java.io.InputStream)new java.net.URL(url).getContent()));
        } catch (Exception e) {
                return null;
        }
    
       }
     }
    

    这里是 URL Image widget 配置类

        public class URLImageAppWidgetConfiguration extends Activity {
        private int id;
    
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.configuration);
            setResult(RESULT_CANCELED);
    
            Intent intent = getIntent();
            Bundle extras = intent.getExtras();
            if (extras != null) {
                id = extras.getInt(
                        AppWidgetManager.EXTRA_APPWIDGET_ID, 
                        AppWidgetManager.INVALID_APPWIDGET_ID);
            }
    
            if (id == AppWidgetManager.INVALID_APPWIDGET_ID) {
            finish();
        }
    
        }
    
        public void addWidget(View v) {
                SharedPreferences urls = getSharedPreferences("urls.conf", Context.MODE_PRIVATE);
                SharedPreferences.Editor urls_editor = urls.edit();
    
                String url = ((TextView) findViewById(R.id.url)).getText().toString();
                if (!url.startsWith("http://")) url = "http://" + url;
                urls_editor.putString("url_" + id, url);
                urls_editor.commit();
    
                AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
                URLImageAppWidgetProvider.update(this, appWidgetManager, id, url);
    
        setResult(RESULT_OK, 
                          new Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id)
        );
        finish();
        }
       }
    

    【讨论】:

    • 哦,对不起。现在的问题是我无法从 url 加载图像并显示到 ImageView。 remoteViews.setImageViewBitmap(R.id.widget_background, getBitmapFromUrl("https://www.getchopink.com/assets/default/images/for-your-business-6.png"));这是你提供给我的方法
    • 可以使用此方法从URLprivate static Bitmap getBitmapFromUrl(final String url) { try { return BitmapFactory.decodeStream(((java.io.InputStream)new java.net.URL(url).getContent())); } catch (Exception e) { return null; }获取图片
    • 是的,我正在调用此方法,但它返回 null。 e.getMessage() 还有null
    【解决方案3】:

    看这个。

    How to create android app with app widget in single application

    如果您发现任何问题,这对您很有帮助,请告诉我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-22
      • 1970-01-01
      相关资源
      最近更新 更多