简体   繁体   中英

Android AppWidget: Add Custom Views to Widget Layout

I want to show some list of TextView and EditView in my Widget.

I used the following code to generate list of TextView and EditView

public LinearLayout getMainBodyLayout(List<Item> data) {
        LinearLayout mainLL = new LinearLayout(context);
        mainLL.setOrientation(LinearLayout.VERTICAL);
        for (int i = 0; i < data.size(); i++) {
            Item ritem = data.get(i);
            LinearLayout item = new LinearLayout(context);
            TextView name = new TextView(context);
            EditText nos = new EditText(context);
            name.setText(ritem.getName());
            nos.setText(ritem.getNo());
            item.addView(name);
            item.addView(nos);
            mainLL.addView(item);

        }

        return mainLL;
    }

public void updateWidget(LinearLayout ll) {
        AppWidgetManager manager = AppWidgetManager.getInstance(context);
        ComponentName thisWidget = new ComponentName(context, MainWidget.class);
        RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
                R.layout.widget_my);
        remoteViews.setTextViewText(R.id.title, title);

        remoteViews.setTextViewText(R.id.widget_error, errorMsg);

// I ve to add ll to this remoteViews


        manager.updateAppWidget(thisWidget, remoteViews);
    }

I have to add the returned LinearLayout to my widget Linearlayout. Please provide me the best way to do this.

Try to make Layout in XMl and set its value in Java file... and use method

          RemoteViews.setTextviewText(id,string);

try this method as i hv use it in my widget

        private class ABC extends TimerTask {
         RemoteViews remoteViews;
         AppWidgetManager appWidgetManager;
         ComponentName thisWidget;

         public ABC(Context context, final AppWidgetManager appWidgetManager) {
         this.appWidgetManager = appWidgetManager;


         remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
         thisWidget = new ComponentName(context, WidgetAnimate.class);
          }

         public void run() {

           String k= XMLfunctions.data1();   
           remoteViews.setTextViewText(R.id.tv12,k);
           appWidgetManager.updateAppWidget(thisWidget, remoteViews);

         }

Giving you a full code for that will be much bigger. I am giving you some code sample you can optimize it as you needed.

Android ListView example .

And this one is also a good tutorial to start with

Android ListView Tutorial

And if you want optimized your list you can see this tutorial.

ListView Tips & Tricks #3: Create Fancy ListViews

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM