Android |从另一个(非活动)类启动PopupWindow

时间:2017-10-23 23:12:27

标签: java android popupwindow

我目前正在构建一个需要大量弹出窗口的应用程序,并且MainActivity.java开始变得有点凌乱。我想将弹出窗口的初始化卸载到另一个类。这是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);


}


}

感谢所有帮助。提前谢谢。

1 个答案:

答案 0 :(得分:1)

以下是我创建警报对话框的方法,您必须修改弹出窗口的代码,但想法是一样的。

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();
}

然后从我的活动我可以称之为

DialogUtils.generateDialog(this, "title", "message", <OnclickListener>, <OnClickListener>).show();

特别是在你的代码中,你必须用布局inflater替换AlertDialog.Builder(使用getLayoutInflater()),然后代替DialogInterface.OnClickListener,你需要为你的按钮带一个View.OnClickListener