我正在使用配置活动来使用 RemoteViews 切换 xml 文件中不同视图的可见性。起初我想,由于在设置小部件之前调用了配置活动,我不需要更新,所以我使用了:
package com.example.test.clock.one;
import android.app.Activity;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.RemoteViews;
public class chooseract extends Activity
{
int mAppWidgetId;
RemoteViews rv;
AppWidgetManager appWidgetManager;
Context context;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void buttonhandler(View view)
{
rv = new RemoteViews(context.getPackageName(), R.layout.activity_main);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null)
{
mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,AppWidgetManager.INVALID_APPWIDGET_ID);
}
switch(view.getId())
{
case R.id.button1:
{
rv.setViewVisibility(R.id.analogClock1, View.VISIBLE);
rv.setViewVisibility(R.id.analogClock2, View.INVISIBLE);
finish();
break;
}
case R.id.button2:
{
rv.setViewVisibility(R.id.analogClock1, View.INVISIBLE);
rv.setViewVisibility(R.id.analogClock2, View.VISIBLE);
finish();
break;
}
}
}
}
但这只是设置了一个空白小部件(默认可见性是不可见的)然后我尝试在使用切换可见性后更新 appwidget
package com.example.test.clock.one;
import android.app.Activity;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.RemoteViews;
public class chooseract extends Activity
{
int mAppWidgetId;
RemoteViews rv;
AppWidgetManager appWidgetManager;
Context context;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void buttonhandler(View view)
{
rv = new RemoteViews(context.getPackageName(), R.layout.activity_main);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null)
{
mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,AppWidgetManager.INVALID_APPWIDGET_ID);
}
switch(view.getId())
{
case R.id.button1:
{
rv.setViewVisibility(R.id.analogClock1, View.VISIBLE);
rv.setViewVisibility(R.id.analogClock2, View.INVISIBLE);
break;
}
case R.id.button2:
{
rv.setViewVisibility(R.id.analogClock1, View.INVISIBLE);
rv.setViewVisibility(R.id.analogClock2, View.VISIBLE);
break;
}
}
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
appWidgetManager.updateAppWidget(mAppWidgetId, rv);
Intent resultValue = new Intent();
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
setResult(RESULT_OK, resultValue);
finish();
}
}
但这只是当我用 NullPointerException 触摸按钮时强制关闭有什么想法吗?