Google Maps and RecyclerView

问题描述 投票:0回答:1

我对Android Studio来说还很陌生,因此为菜鸟的错误道歉。我正在使用Google Map SDK制作一个Android应用程序,并希望使用RecyclerView保存旧的搜索,一旦单击旧的保存位置,它将放大到该位置。但是,我在editText框中的输入没有保存到RecyclerView中。

编辑:显然,使用ListView是完成此任务的简便方法,我从未使用过

这是我的主班:

public class MapsActivity extends AppCompatActivity
implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener
{

  public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
  GoogleMap mGoogleMap;
  SupportMapFragment mapFrag;
  LocationRequest mLocationRequest;
  GoogleApiClient mGoogleApiClient;
  Location mLastLocation;
  Marker mCurrLocationMarker;
  EditText editText;
  Button searchLocation;
  Geocoder geocoder;
  List<Address> addresses = new ArrayList<>();
  double lat, lng;
  //ArrayList<Address> address;



  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    editText = findViewById(R.id.editText);
    searchLocation = findViewById(R.id.searchLocation);

    RecyclerView recycler_view = (RecyclerView) findViewById(R.id.recycler_view) ;
    MyAdapter myAdapter = new MyAdapter((ArrayList<Address>) addresses);
    recycler_view.setAdapter(myAdapter);


    mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
    mapFrag.getMapAsync(this);
    geocoder = new Geocoder(this, Locale.getDefault());

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
      mGoogleMap = googleMap;
      mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

      //Initialize Google Play Services
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) 
      {
          if (ContextCompat.checkSelfPermission(this,
                 android.Manifest.permission.ACCESS_FINE_LOCATION)
                 == PackageManager.PERMISSION_GRANTED) {
              buildGoogleApiClient();
              mGoogleMap.setMyLocationEnabled(true);   }

      } else {
          buildGoogleApiClient();
          mGoogleMap.setMyLocationEnabled(true);
        }

      searchLocation.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
            try {
                   addresses = geocoder.getFromLocationName(editText.getText().toString(), 1);
                } catch (IOException e) {
                e.printStackTrace();
                }

                if (addresses.size()>0) {
                   Address address = addresses.get(0);
                   LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
                   mGoogleMap.addMarker(new MarkerOptions().position(latLng).title(String.valueOf(searchLocation)));
                   mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
                }
                else{
                   Toast.makeText(getApplicationContext(),"Invalid Address!",Toast.LENGTH_SHORT).show();
                }
             }
          });
        }

         protected synchronized void buildGoogleApiClient() 
         {
             mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
             mGoogleApiClient.connect();
         }

         @Override
         public void onConnected(Bundle bundle) {
           mLocationRequest = new LocationRequest();
           mLocationRequest.setInterval(1000);
           mLocationRequest.setFastestInterval(1000);
           mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
           if (ContextCompat.checkSelfPermission(this,
            android.Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
              LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);}

     }

     @Override
     public void onConnectionSuspended(int i) {
     }

     @Override
     public void onConnectionFailed(ConnectionResult connectionResult) {
     }

     @Override
     public void onLocationChanged(Location location) {
        mLastLocation = location;
        if (mCurrLocationMarker != null) {
        mCurrLocationMarker.remove();
      }
   }
}

这是我的适配器类:

    public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private ArrayList<MarkerOptions> markerList;
private LayoutInflater mInflater;
private static itemClickListener listener;  //Listener object, using the interface

public MyAdapter(ArrayList<Address> addresses) {
}


//Create an interface used for creating a click listener
//Reference: https://stackoverflow.com/questions/24471109/recyclerview-onclick/26196831#26196831
public interface itemClickListener{
    public void onItemClick(View v, int pos);
}


//Provides a reference to the views for each data item - View holder
public static class MyViewHolder extends RecyclerView.ViewHolder {
    public TextView editText;

    public MyViewHolder(@NonNull View itemView) {
        super(itemView);
        editText = itemView.findViewById(R.id.editText);

        //Override the click listener for listening to each click on the root view of the item(main activity)
        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Acquires the position of the click on the root view
                int position = MyViewHolder.super.getAdapterPosition();

                //Trigger callback
                listener.onItemClick(v, position);
            }
        });

    }
}

//Adapter Constructor
public MyAdapter(Context context, ArrayList<MarkerOptions> input, itemClickListener listen){
    mInflater = LayoutInflater.from(context);
    markerList = input;
    listener = listen;
}

//Create new views, invoked by layout manager
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    //Create new view
    View v = mInflater.inflate(R.layout.history_locations, parent,
            false);

    return new MyViewHolder(v);
}

//Replaces the content of a view, invoked by layout manager
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, final int position) {
    String tempTitle = markerList.get(position).getTitle();
    holder.editText.setText(tempTitle);

}

@Override
public int getItemCount() {
    return markerList.size();
}
}

和我的XML文件

    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MapsActivity">

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

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

            <EditText
                android:layout_width="248dp"
                android:layout_height="wrap_content"
                android:id="@+id/editText"
                android:layout_weight="0.5"
                android:inputType="textPersonName"
                android:hint="Search Location" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="0.5"
                android:id="@+id/searchLocation"
                android:text="Search" />

        </LinearLayout>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="160dp"
        android:layout_alignParentBottom="true"
        android:background="@android:color/background_light"/>

</RelativeLayout>
android android-studio google-maps android-recyclerview google-maps-markers
1个回答
0
投票

在您的adapter

public MyAdapter(ArrayList<Address> addresses) {

//add this
this. markerList = addresses;

}

MapsActivity

移动这些行:

MyAdapter myAdapter = new MyAdapter((ArrayList<Address>) addresses);
recycler_view.setAdapter(myAdapter);

//在您的点击监听器中

........
try {
addresses = geocoder.getFromLocationName(editText.getText().toString(), 1);
//here
MyAdapter myAdapter = new MyAdapter((ArrayList<Address>) addresses);
recycler_view.setAdapter(myAdapter);

} catch (IOException e) {
e.printStackTrace();
}
......
.......
© www.soinside.com 2019 - 2024. All rights reserved.