Android |从另一个(非 activity)class 启动 PopupWindow
Android | Initiate PopupWindow from another (non activity) class
我目前正在构建一个需要大量弹出窗口的应用程序,MainActivity.java 开始变得有点混乱。我想将弹出窗口的初始化卸载到另一个 class。这里是 MainActivity.Java。我想尝试卸载的方法是 PopupNYC();
public class MainActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMarkerClickListener {
static LinearLayout mainLayout;
private GoogleMap mMap;
PlaceAutocompleteFragment placeAutoComplete;
private static final String TAG = "Main Activity";
List<Marker> list = new ArrayList<>();
public static AdView mAdView;
//TODO: add markers here!
Marker NY_CITY;
public static PopupWindow popupWindow;
public static LayoutInflater layoutInflater;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(getApplicationContext(), "APP_KEY");
//TODO:initialize startup stuff here:
/*
* layoutTest is the testing inflater for all popup windows.
* here is where new popup windows will be added to the list.
* */
mainLayout = (LinearLayout) findViewById(R.id.mainLayout);
AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
.setTypeFilter(AutocompleteFilter.TYPE_FILTER_CITIES)
.build();
placeAutoComplete = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_autocomplete);
placeAutoComplete.setFilter(typeFilter);
placeAutoComplete.setOnPlaceSelectedListener(new PlaceSelectionListener() {
@Override
public void onPlaceSelected(Place place) {
Log.i(TAG, "Place Selected: " + place.getName());
LatLng latLng = place.getLatLng();
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11));
//TODO: open window depending on selected place, and throw error box if not supported.
//Hey you! you need to limit this to cities/towns somehow.
if (place.getName().equals("New York"))
{
PopupNYC();
}
else
{
PopupNotProvided();
}
}
@Override
public void onError(Status status) {
Log.d("Maps", "An error occurred: " + status);
}
});
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
try {
// Customise the styling of the base map using a JSON object defined
// in a raw resource file.
boolean success = googleMap.setMapStyle(
MapStyleOptions.loadRawResourceStyle(
this, R.raw.style_json));
if (!success) {
Log.e(TAG, "Style parsing failed.");
}
} catch (Resources.NotFoundException e) {
Log.e(TAG, "Can't find style. Error: ", e);
}
//TODO: DEFINE MARKER LOCATIONS HERE:
LatLng nycLoc = new LatLng(40.754932, -73.984016);
//TODO: INIT MARKERS HERE:
NY_CITY = googleMap.addMarker(new MarkerOptions().position(nycLoc).title("New York City").snippet("New York City"));
list.add(NY_CITY);
googleMap.setOnCameraChangeListener(new
GoogleMap.OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition cameraPosition) {
for (Marker m : list) {
m.setVisible(cameraPosition.zoom > 10); // <-- define zoom level for markers here
/**
* Zoom level guidelines:
* 12 = zoomed in about 90%
* 1 = zommed in less than 5%
* Higher = higher zoom, Lower = lower zoom.
* Confusing. I know.
*/
}
}
});
mMap.setOnMarkerClickListener(this);
}
//TODO: handle marker clicks below:
/*
* current placeholder code states that all markers
* will open the popup_test layout.
* */
public boolean onMarkerClick(Marker arg0)
{
if (arg0.equals(NY_CITY))
{
PopupNYC();
return true;
}
/*if all else fails, return false
*/
return false;
}
//TODO: initialize popup initialization below:
public void PopupNotProvided()
{
layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
ViewGroup container = (ViewGroup) layoutInflater.inflate(R.layout.popup_no_town,null);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int popWidth = dm.widthPixels;
int popHeight = dm.heightPixels;
popupWindow = new PopupWindow(container,(int) (popWidth*.9),(int) (popHeight*.7),true);
mAdView = (AdView) popupWindow.getContentView().findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
final Button button = container.findViewById(R.id.buttonSuggest);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("google.com"));
startActivity(browserIntent);
Log.d(TAG, "User chose to submit location!");
}
});
final Button buttonDis = container.findViewById(R.id.buttonDismiss);
buttonDis.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
popupWindow.dismiss();
Log.d(TAG, "User chose to dismiss error. :(");
}
});
popupWindow.setFocusable(true);
popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
popupWindow.setOutsideTouchable(true);
popupWindow.showAtLocation(mainLayout, Gravity.CENTER,0,0);
}
public void PopupNYC()
{
layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
ViewGroup container = (ViewGroup) layoutInflater.inflate(R.layout.popup_test,null);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int popWidth = dm.widthPixels;
int popHeight = dm.heightPixels;
popupWindow = new PopupWindow(container,(int) (popWidth*.9),(int) (popHeight*.7),true);
mAdView = (AdView) popupWindow.getContentView().findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
popupWindow.setFocusable(true);
popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
popupWindow.setOutsideTouchable(true);
popupWindow.showAtLocation(mainLayout, Gravity.CENTER,0,0);
}
}
感谢所有帮助。提前致谢。
这是我创建警报对话框的方法,您必须修改弹出窗口的代码,但思路是一样的。
public static AlertDialog generateDialog(Context ctx,
String title,
String message,
@NonNull DialogInterface.OnClickListener positiveClick,
DialogInterface.OnClickListener negativeClick) {
AlertDialog.Builder adb = new AlertDialog.Builder(ctx);
adb.setTitle(title);
adb.setMessage(message);
adb.setPositiveButton(ctx.getString(R.string.alert_ok), positiveClick);
if(negativeClick != null) {
adb.setNegativeButton(ctx.getString(R.string.alert_cancel), negativeClick);
}
else {
adb.setNegativeButton(ctx.getString(R.string.alert_cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
return adb.create();
}
然后从我的 Activity 我可以这样称呼它
DialogUtils.generateDialog(this, "title", "message", <OnclickListener>, <OnClickListener>).show();
特别是在您的代码中,您必须将 AlertDialog.Builder 替换为布局充气器(使用 getLayoutInflater()
),然后您需要使用 DialogInterface.OnClickListener,而不是 DialogInterface.OnClickListener View.OnClickListener 用于您的按钮。
我目前正在构建一个需要大量弹出窗口的应用程序,MainActivity.java 开始变得有点混乱。我想将弹出窗口的初始化卸载到另一个 class。这里是 MainActivity.Java。我想尝试卸载的方法是 PopupNYC();
public class MainActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMarkerClickListener {
static LinearLayout mainLayout;
private GoogleMap mMap;
PlaceAutocompleteFragment placeAutoComplete;
private static final String TAG = "Main Activity";
List<Marker> list = new ArrayList<>();
public static AdView mAdView;
//TODO: add markers here!
Marker NY_CITY;
public static PopupWindow popupWindow;
public static LayoutInflater layoutInflater;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(getApplicationContext(), "APP_KEY");
//TODO:initialize startup stuff here:
/*
* layoutTest is the testing inflater for all popup windows.
* here is where new popup windows will be added to the list.
* */
mainLayout = (LinearLayout) findViewById(R.id.mainLayout);
AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
.setTypeFilter(AutocompleteFilter.TYPE_FILTER_CITIES)
.build();
placeAutoComplete = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_autocomplete);
placeAutoComplete.setFilter(typeFilter);
placeAutoComplete.setOnPlaceSelectedListener(new PlaceSelectionListener() {
@Override
public void onPlaceSelected(Place place) {
Log.i(TAG, "Place Selected: " + place.getName());
LatLng latLng = place.getLatLng();
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11));
//TODO: open window depending on selected place, and throw error box if not supported.
//Hey you! you need to limit this to cities/towns somehow.
if (place.getName().equals("New York"))
{
PopupNYC();
}
else
{
PopupNotProvided();
}
}
@Override
public void onError(Status status) {
Log.d("Maps", "An error occurred: " + status);
}
});
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
try {
// Customise the styling of the base map using a JSON object defined
// in a raw resource file.
boolean success = googleMap.setMapStyle(
MapStyleOptions.loadRawResourceStyle(
this, R.raw.style_json));
if (!success) {
Log.e(TAG, "Style parsing failed.");
}
} catch (Resources.NotFoundException e) {
Log.e(TAG, "Can't find style. Error: ", e);
}
//TODO: DEFINE MARKER LOCATIONS HERE:
LatLng nycLoc = new LatLng(40.754932, -73.984016);
//TODO: INIT MARKERS HERE:
NY_CITY = googleMap.addMarker(new MarkerOptions().position(nycLoc).title("New York City").snippet("New York City"));
list.add(NY_CITY);
googleMap.setOnCameraChangeListener(new
GoogleMap.OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition cameraPosition) {
for (Marker m : list) {
m.setVisible(cameraPosition.zoom > 10); // <-- define zoom level for markers here
/**
* Zoom level guidelines:
* 12 = zoomed in about 90%
* 1 = zommed in less than 5%
* Higher = higher zoom, Lower = lower zoom.
* Confusing. I know.
*/
}
}
});
mMap.setOnMarkerClickListener(this);
}
//TODO: handle marker clicks below:
/*
* current placeholder code states that all markers
* will open the popup_test layout.
* */
public boolean onMarkerClick(Marker arg0)
{
if (arg0.equals(NY_CITY))
{
PopupNYC();
return true;
}
/*if all else fails, return false
*/
return false;
}
//TODO: initialize popup initialization below:
public void PopupNotProvided()
{
layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
ViewGroup container = (ViewGroup) layoutInflater.inflate(R.layout.popup_no_town,null);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int popWidth = dm.widthPixels;
int popHeight = dm.heightPixels;
popupWindow = new PopupWindow(container,(int) (popWidth*.9),(int) (popHeight*.7),true);
mAdView = (AdView) popupWindow.getContentView().findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
final Button button = container.findViewById(R.id.buttonSuggest);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("google.com"));
startActivity(browserIntent);
Log.d(TAG, "User chose to submit location!");
}
});
final Button buttonDis = container.findViewById(R.id.buttonDismiss);
buttonDis.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
popupWindow.dismiss();
Log.d(TAG, "User chose to dismiss error. :(");
}
});
popupWindow.setFocusable(true);
popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
popupWindow.setOutsideTouchable(true);
popupWindow.showAtLocation(mainLayout, Gravity.CENTER,0,0);
}
public void PopupNYC()
{
layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
ViewGroup container = (ViewGroup) layoutInflater.inflate(R.layout.popup_test,null);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int popWidth = dm.widthPixels;
int popHeight = dm.heightPixels;
popupWindow = new PopupWindow(container,(int) (popWidth*.9),(int) (popHeight*.7),true);
mAdView = (AdView) popupWindow.getContentView().findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
popupWindow.setFocusable(true);
popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
popupWindow.setOutsideTouchable(true);
popupWindow.showAtLocation(mainLayout, Gravity.CENTER,0,0);
}
}
感谢所有帮助。提前致谢。
这是我创建警报对话框的方法,您必须修改弹出窗口的代码,但思路是一样的。
public static AlertDialog generateDialog(Context ctx,
String title,
String message,
@NonNull DialogInterface.OnClickListener positiveClick,
DialogInterface.OnClickListener negativeClick) {
AlertDialog.Builder adb = new AlertDialog.Builder(ctx);
adb.setTitle(title);
adb.setMessage(message);
adb.setPositiveButton(ctx.getString(R.string.alert_ok), positiveClick);
if(negativeClick != null) {
adb.setNegativeButton(ctx.getString(R.string.alert_cancel), negativeClick);
}
else {
adb.setNegativeButton(ctx.getString(R.string.alert_cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
return adb.create();
}
然后从我的 Activity 我可以这样称呼它
DialogUtils.generateDialog(this, "title", "message", <OnclickListener>, <OnClickListener>).show();
特别是在您的代码中,您必须将 AlertDialog.Builder 替换为布局充气器(使用 getLayoutInflater()
),然后您需要使用 DialogInterface.OnClickListener,而不是 DialogInterface.OnClickListener View.OnClickListener 用于您的按钮。