我有一个典型的偏好设置示例,我想调用MainActivity
方法隐藏ImageView
。
But it does not go to debug even.
那么如何正确调用MainActivity
的方法?
public class SettingsActivity extends AppCompatPreferenceActivity
...
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
try {
if (key.equals("isGPS_Switch")) {
Boolean isGPSSwitch = sharedPreferences.getBoolean(key, false);
if (isGPSSwitch) {
// START SERVICE
getActivity().startService(new Intent(getActivity(), gpsService.class));
((MainActivity)getActivity()).MyLocationMapDisplay(true);
} else {
// STOP SERVICE
getActivity().stopService(new Intent(getActivity(), gpsService.class));
((MainActivity)getActivity()).MyLocationMapDisplay(false);
}
}
} catch (Exception ex) {
Log.e("Preferences", ex.getMessage());
}
}
和MAinActivity类
public class MainActivity extends AppCompatActivity
...
private ImageView imageDisplayGPS;
public void MyLocationMapDisplay(boolean isDisplay)
{
if(isDisplay)
{
imageDisplayGPS.setVisibility(View.VISIBLE);
}
else
{
imageDisplayGPS.setVisibility(View.GONE);
}
}
答案 0 :(得分:0)
没有比使用 BroadcastReciver
更简单的了private void configureBroadcastReciver() {
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent i)
{
try
{
String imageDisplayGPSState = (String) i.getExtras().get("btn_imageDisplayGPS");
if(imageDisplayGPSState.equals("true"))
{
MyLocationMapDisplay(true);
}
else
{
MyLocationMapDisplay(false);
}
}
catch (Exception ex)
{
Log.d("MAIN ACTIVITY", ex.getMessage());
}
}
};
registerReceiver(broadcastReceiver, new IntentFilter("buttons_visible"));
}
在首选项中
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
try {
if (key.equals("isGPS_Switch")) {
Boolean isGPSSwitch = sharedPreferences.getBoolean(key, false);
if (isGPSSwitch) {
// START SERVICE
getActivity().startService(new Intent(getActivity(), gpsService.class));
Intent buttons_visible = new Intent("buttons_visible");
buttons_visible.putExtra("btn_imageDisplayGPS", "true");
getContext().sendBroadcast(buttons_visible);
} else {
// STOP SERVICE
getActivity().stopService(new Intent(getActivity(), gpsService.class));
Intent buttons_visible = new Intent("buttons_visible");
buttons_visible.putExtra("btn_imageDisplayGPS", "false");
getContext().sendBroadcast(buttons_visible);
}
}
} catch (Exception ex) {
Log.e("Preferences", ex.getMessage());
}
}
}