从数组中获取数据并从小部件传递到活动,而无需列表视图

时间:2018-07-10 15:36:32

标签: java android android-widget android-pendingintent android-appwidget

Listview是可滚动的,因此通过动态调整其行的大小与父项不匹配。是否可以从数组中获取数据并将其分别传递给活动,以便我可以改用LinearLayout

RemoteViews mainView = new RemoteViews(context.getPackageName(), R.layout.main_widget_layout);
    for (int i = 0; i < 16; i++) {
        RemoteViews textView = new RemoteViews(context.getPackageName(), R.layout.text_append_layout);
        textView.setTextViewText(R.id.appending_text, String.valueOf(i));
        mainView.addView(R.id.text_data_viewer, textView);

        Intent fillInIntent = new Intent();
        fillInIntent.putExtra("extradata", i);
        textView.setOnClickFillInIntent(R.id.appending_text, fillInIntent);
    }
Intent activitytoStart = new Intent(context, Widget.class).setAction("com.custom.action");
mainView.setPendingIntentTemplate(R.id.text_data_viewer, PendingIntent.getBroadcast(context, 0, activitytoStart, PendingIntent.FLAG_UPDATE_CURRENT));

main_widget_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/text_data_viewer"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:weightSum="16"
                android:orientation="vertical"/>

text_append_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/appending_text"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:gravity="center" />

1 个答案:

答案 0 :(得分:0)

首先,您为什么不使用remoteviewsfactory?这将使填充列表视图变得更加容易。

但要回答您的问题-要将数据从小部件传递到活动,则需要按意图传递数据,因此,当您单击小部件时,它将打开活动。 设置具有待定意图的小部件:

        Intent clickIntentTemplate = new Intent(context, MainActivity.class);

        clickIntentTemplate.setAction(Intent.ACTION_MAIN);
        clickIntentTemplate.addCategory(Intent.CATEGORY_LAUNCHER);
        clickIntentTemplate.putExtra("extraName",extra);
        clickIntentTemplate.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        PendingIntent configPendingIntent = PendingIntent.getActivity(context, 0, clickIntentTemplate, PendingIntent.FLAG_UPDATE_CURRENT);
        views.setOnClickPendingIntent(R.id.widget_view, configPendingIntent);

检索活动意图:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (getIntent().getExtras() != null) {
        String retrievedString = getIntent().getExtras().getString("extraName");
    }
    //...rest of your code
}

还要在onNewIntent()中包含该方法:

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);

    if (getIntent().getExtras() != null) {
        String retrievedString = getIntent().getExtras().getString("extraName");
    }
}