我是Android开发的新手。我正在尝试为我的应用程序创建一个包含listview的小部件,每个listview除了标题和内容之外还有2个按钮。
当我按下该元素的按钮时,我试图在app小部件(主屏幕)中隐藏listitem的相应元素。
首先,我尝试检查按钮点击是否得到任何响应,如果我能检测到我是否可以获得该项目的位置。所以我这样做了:
listprovider.java(实现remoteviewfactory):
@Override
public RemoteViews getViewAt(int position) {
final RemoteViews remoteView = new RemoteViews(
context.getPackageName(), R.layout.list_row);
ListItem listItem = listItemList.get(position);
remoteView.setTextViewText(R.id.heading, listItem.heading);
remoteView.setTextViewText(R.id.content, listItem.content);
Bundle extras = new Bundle();
extras.putInt(WidgetProvider.EXTRA_ITEM, position);
Intent fillInIntent = new Intent();
fillInIntent.putExtras(extras);
// Make it possible to distinguish the individual on-click
// action of a given item
remoteView.setOnClickFillInIntent(R.id.buttonwidget, fillInIntent);
return remoteView;
}
然后在 WidgetProvider.java(扩展AppWidgetProvider):
for (int i = 0; i < N; ++i) {
RemoteViews remoteViews = updateWidgetListView(context,
appWidgetIds[i]);
Intent clickIntent = new Intent(context, MainActivity.class);
clickIntent.setAction(WidgetProvider.TOAST_ACTION);
clickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
clickIntent.setData(Uri.parse(clickIntent.toUri(Intent.URI_INTENT_SCHEME)));
PendingIntent clickPI = PendingIntent.getActivity(context, 0,
clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setPendingIntentTemplate(com.example.markup.R.id.listViewWidget, clickPI);
appWidgetManager.updateAppWidget(appWidgetIds[i], remoteViews);
}
super.onUpdate(context, appWidgetManager, appWidgetIds);
mainActivity.java 是该程序的默认活动,我这样做是为了获取项目位置:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Printing detail of clicked item from widget
Intent intent = getIntent();
if (intent.getAction().equals(WidgetProvider.TOAST_ACTION)) {
int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
int viewIndex = intent.getIntExtra(WidgetProvider.EXTRA_ITEM, 0);
Toast.makeText(getApplicationContext(), "Touched view " + viewIndex, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Touched view none ", Toast.LENGTH_SHORT).show();
}
}
因此我可以通过点击按钮打开主要活动并在底部获取TOAST文本,从而得到准确的结果。
但我希望在点击时隐藏/禁用app小部件的相应元素。我该怎么做?
答案 0 :(得分:0)
you must remove list item from the adapter when the button is pressed. And call
adapter.notifyDataSetChanged();
then the item will disappear. Hopes this can help.