Android 4.2.2 Map Fragment Issue

时间:2016-07-22 09:38:28

标签: android google-maps android-coordinatorlayout supportmapfragment mapfragment

我有一个带工具栏的地图和一个坐标布局的自动完成搜索栏。在4.x以上的Android版本中一切正常,但在Android 4.2.2中,只显示地图。工具栏和自动完成文本视图未显示。

  

请帮助我理解为什么会这样。

Xml

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<RelativeLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <include
        android:id="@+id/toolbar"
        layout="@layout/activity_self_assigned_toolbar" />

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginEnd="10dp"
        android:layout_marginStart="10dp"
        android:layout_marginTop="60dp"
        android:background="#FFFF"
        android:weightSum="1">


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="horizontal">

            <AutoCompleteTextView
                android:id="@+id/autocomplete"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_gravity="bottom"
                android:layout_weight="0.5"
                android:hint="Type in your Location">

            </AutoCompleteTextView>


            <ImageView
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_gravity="center"
                android:layout_weight="0"
                android:id="@+id/custom_map_cross"
                android:src="@drawable/icn_close"/>



            <!--<Button-->
            <!--android:id="@+id/search_button"-->
            <!--android:layout_width="20dp"-->
            <!--android:layout_weight="0.5"-->
            <!--android:layout_height="40dp"-->
            <!--android:layout_marginRight="5dp"-->
            <!--android:layout_gravity="center"-->
            <!--android:padding="5dp"-->
            <!--android:background="@color/indigo_500"-->
            <!--android:textColor="@android:color/white"-->
            <!--android:text="Save" />-->
        </LinearLayout>


    </android.support.design.widget.AppBarLayout>


    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>

map.java:

 public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
                View view = inflater.inflate(R.layout.custom_map_layout,container,false);
                ButterKnife.inject(this,view);
        //        view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
        //                ViewGroup.LayoutParams.MATCH_PARENT));
                // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        //        SupportMapFragment mapFragment = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map);
        //        mMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map))
        //                .getMap();
                initialise();
                initialiseListeners();
                autoCompView.setAdapter(new GooglePlacesAutocompleteAdapter(getActivity(), R.layout.map_single_item));
                autoCompView.setOnItemClickListener(this);
                saveButton.setOnClickListener(this);
                cancelButton.setOnClickListener(this);
                return view;
            }


            private void initialise() {
        //        toolbar.setNavigationIcon(R.drawable.ic_keyboard_arrow_left_black_24dp);
                activity = (AppCompatActivity) getActivity();

                toolbar.setTitle("Address");
            }

            private void initialiseListeners() {
                toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        getActivity().onBackPressed();
                    }
                });
            }

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                View view1 = getActivity().getCurrentFocus();
                if (view1 != null) {
                    InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(view1.getWindowToken(), 0);
                }
        // and next place it, for exemple, on bottom right (as Google Maps app)

                str = (String) parent.getItemAtPosition(position);
        //        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
                getLocationFromAddress(str);
                if (latitude != null && longitude != null) {
                    LatLng latLng = new LatLng(latitude, longitude);
                    mMap.addMarker(new MarkerOptions().position(latLng));
                    CameraPosition pos = CameraPosition.builder()
                            .target( latLng)
                            .zoom( 12f )
                            .bearing( 0.0f )
                            .tilt( 0.0f )
                            .build();

                    mMap.setMyLocationEnabled(true);
                    mMap.animateCamera( CameraUpdateFactory
                            .newCameraPosition( pos ), null );
                }
            }

            public void getLocationFromAddress(String strAddress) {

                Geocoder coder = new Geocoder(context);
                List<Address> address;

                try {
                    address = coder.getFromLocationName(strAddress, 5);
                    if (address != null) {

                        Address location = address.get(0);
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.self_assignment_save_textview:
                        new generateCheckinsTask(context).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                        break;

                    case R.id.self_assignment_cancel_textview:
        //
        //                getActivity().getSupportFragmentManager().popBackStack();

                        break;

                }

            }

            private class generateCheckinsTask extends AsyncTask {
                private Context context;

                generateCheckinsTask(Context context) {
                    this.context = context;
                }


                @Override
                protected Object doInBackground(Object[] params) {

                    return null;

                }

                @Override
                protected void onPostExecute(Object o) {
                    super.onPostExecute(o);

                    Time time = new Time();
                    time.setToNow();

                    Fragment_Self_Assignment self_assignment = new Fragment_Self_Assignment();
                    self_assignment.updateAddress(str,latitude,longitude);

                    Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                        public void run() {

        //                    if (materialDialog != null && materialDialog.isShowing()) {
        //                        materialDialog.dismiss();
        //                    }
                            getActivity().finish();

                        }
                    }, 500);

                }

                @Override
                protected void onPreExecute() {
                    super.onPreExecute();

                }
            }

            @Override
            public void onResume() {


                Spannable actionBarTitle = new SpannableString("Add Place");
                actionBarTitle.setSpan(
                        new ForegroundColorSpan(Color.WHITE),
                        0,
                        actionBarTitle.length(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                if(((AppCompatActivity) getActivity()).getSupportActionBar() != null){

                    ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(actionBarTitle);
                    InputMethodManager imm = (InputMethodManager) getActivity()
                            .getSystemService(Context.INPUT_METHOD_SERVICE);

                    if(!imm.isAcceptingText()){
                        imm.hideSoftInputFromWindow(getView().getWindowToken(),0);
                    }

                }
                super.onResume();
            }

            @Override
            public void onStart() {
                super.onStart();
                if (activity.getSupportActionBar().isShowing())
                    activity.getSupportActionBar().hide();
            }
            @Override
            public void onStop() {
                super.onStop();
                if (!activity.getSupportActionBar().isShowing())
                    activity.getSupportActionBar().show();
            }

     public static ArrayList autocomplete(String input) {
            ArrayList resultList = null;
            HttpURLConnection conn = null;
            StringBuilder jsonResults = new StringBuilder();

            try {
                StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
                sb.append("?key=" + API_KEY);
    //            sb.append("&components=country:gr");
                sb.append("&input=" + URLEncoder.encode(input, "utf8"));
                URL url = new URL(sb.toString());
                conn = (HttpURLConnection) url.openConnection();
                InputStreamReader in = new InputStreamReader(conn.getInputStream());
                // Load the results into a StringBuilder
                int read;
                char[] buff = new char[1024];
                while ((read = in.read(buff)) != -1) {
                    jsonResults.append(buff, 0, read);
                }
            } catch (MalformedURLException e) {
                Log.e(LOG_TAG, "Error processing Places API URL", e);
                return resultList;
            } catch (IOException e) {
                Log.e(LOG_TAG, "Error connecting to Places API", e);
                return resultList;
            } finally {
                if (conn != null) {
                    conn.disconnect();
                }
            }
            try {
                // Create a JSON object hierarchy from the results
                JSONObject jsonObj = new JSONObject(jsonResults.toString());
                JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
                // Extract the Place descriptions from the results
                resultList = new ArrayList(predsJsonArray.length());
                for (int i = 0; i < predsJsonArray.length(); i++) {
                    System.out.println(predsJsonArray.getJSONObject(i).getString("description"));
                    System.out.println("============================================================");
                    resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
                }
            } catch (JSONException e) {
                Log.e(LOG_TAG, "Cannot process JSON results", e);
            }
            return resultList;
        }    
        }

ISSUE:image(4.2.2版本):

enter image description here

更高版本上相同代码的图片(代码正常工作): enter image description here

2 个答案:

答案 0 :(得分:2)

检查一下

  <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <include
        android:id="@+id/toolbar"
        layout="@layout/toolbar" />

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginEnd="10dp"
        android:layout_marginStart="10dp"
        android:layout_marginTop="60dp"
        android:background="#FFFF"
        android:weightSum="1">


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="horizontal">

            <AutoCompleteTextView
                android:id="@+id/autocomplete"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_gravity="bottom"
                android:layout_weight="0.5"
                android:hint="Type in your Location">

            </AutoCompleteTextView>


            <ImageView
                android:id="@+id/custom_map_cross"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_gravity="center"
                android:layout_weight="0"
                android:src="@drawable/pick_ticket_bg_large" />

        </LinearLayout>


    </android.support.design.widget.AppBarLayout>


</RelativeLayout>

答案 1 :(得分:2)

您的MapFragmentToolBar和自动填充搜索栏重叠,请将其保持在MapFragment之上。

试试这个。

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout android:layout_width="match_parent"
        android:layout_height="match_parent"
        xmlns:android="http://schemas.android.com/apk/res/android">

        <fragment xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/map"
            android:name="com.google.android.gms.maps.SupportMapFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <include
            android:id="@+id/toolbar"
            layout="@layout/activity_self_assigned_toolbar" />

        <android.support.design.widget.AppBarLayout
            android:id="@+id/appbar"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:layout_marginEnd="10dp"
            android:layout_marginStart="10dp"
            android:layout_marginTop="60dp"
            android:background="#FFFF"
            android:weightSum="1">


            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:orientation="horizontal">

                <AutoCompleteTextView
                    android:id="@+id/autocomplete"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_gravity="bottom"
                    android:layout_weight="0.5"
                    android:hint="Type in your Location">

                </AutoCompleteTextView>

                <ImageView
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:layout_gravity="center"
                    android:layout_weight="0"
                    android:id="@+id/custom_map_cross"
                    android:src="@drawable/icn_close"/>

            </LinearLayout>

        </android.support.design.widget.AppBarLayout>

    </RelativeLayout>
</android.support.design.widget.CoordinatorLayout>