2016-08-30 3 views
0

멍청한 질문에 대해 유감이지만 저에게 도움이 될만한 상황을 발견하지 못했습니다. 이것이 매우 간단하다는 것을 확신합니다, 나는 올바른 방향을 가리킬 필요가 있습니다.Android Studio는 재정의 방법으로 XML에서 정보를 검색합니다.

목표 :
사용자가 지정한 이름을 가져 와서 마커 제목에 추가 할 수 있기를 원합니다.

내가 알고있는 무엇 :
내가 방법을 재정의되고있는 나는 더 이상 허용하지 않습니다 내 지식 팽창 경우 나이 메서드를 재정의하게 XML을 팽창 및 그 방법을 통해 그것을 잡아 드릴 수 없습니다. 어떻게 접근해야합니까?

MapsAcitivy

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, addPlace.Communicator { 

    private GoogleMap mMap; 
    public static final int MY_PERMISSION_ACCESS_FINE_LOCATION = 0; 
    int mStackLevel; 
    int YES_NO_CALL; 
    FragmentManager manager = getSupportFragmentManager(); 
    final Context context = this; 

    @InjectView(R.id.btn_login) Button _loginButton; 

    ClusterManager<ClusterRequest> mClusterManager; 


    class CustomInfoWindowAdapter implements GoogleMap.InfoWindowAdapter { 

     // These are both viewgroups containing an ImageView with id "badge" and two TextViews with id 
     // "title" and "snippet". 
     private final View mWindow; 

     //private final View mContents; 

     CustomInfoWindowAdapter() { 
      mWindow = getLayoutInflater().inflate(R.layout.info_window_layout, null); 
      //mContents = getLayoutInflater().inflate(R.layout.custom_info_contents, null); 
     } 

     @Override 
     public View getInfoWindow(Marker marker) { 
      render(marker, mWindow); 
      return mWindow; 
     } 

     @Override 
     public View getInfoContents(Marker marker) { 
      // Getting view from the layout file info_window_layout 
      View v = getLayoutInflater().inflate(R.layout.info_window_layout, null); 

      // Getting the position from the marker 
      LatLng latLng = marker.getPosition(); 

      // Getting reference to the TextView to set latitude 
      TextView tvLat = (TextView) v.findViewById(R.id.tv_lat); 

      // Getting reference to the TextView to set longitude 
      TextView tvLng = (TextView) v.findViewById(R.id.tv_lng); 

      // Setting the latitude 
      tvLat.setText("Latitude:" + latLng.latitude); 

      // Setting the longitude 
      tvLng.setText("Longitude:"+ latLng.longitude); 

      // Returning the view containing InfoWindow contents 
      return v; 
      //render(marker, mContents); 
      //return mContents; 
     } 

     private void render(Marker marker, View view) { 
     } 
    } 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_maps); 
     // Obtain the SupportMapFragment and get notified when the map is ready to be used. 
     SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() 
       .findFragmentById(R.id.map); 
     mapFragment.getMapAsync(this); 
    } 

    @Override 
    @TargetApi(23) 
    public void onMapReady(GoogleMap googleMap) { 
     mMap = googleMap; 

     // Here, thisActivity is the current activity 
     if (ContextCompat.checkSelfPermission(this, 
       Manifest.permission.ACCESS_FINE_LOCATION) 
       != PackageManager.PERMISSION_GRANTED) { 

      // Should we show an explanation? 
      if (ActivityCompat.shouldShowRequestPermissionRationale(this, 
        Manifest.permission.ACCESS_FINE_LOCATION)) { 

       // Show an expanation to the user *asynchronously* -- don't block 
       // this thread waiting for the user's response! After the user 
       // sees the explanation, try again to request the permission. 

      } else { 

       // No explanation needed, we can request the permission. 

       ActivityCompat.requestPermissions(this, 
         new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
         MY_PERMISSION_ACCESS_FINE_LOCATION); 

       // MY_PERMISSION_ACCESS_FINE_LOCATION is an 
       // app-defined int constant. The callback method gets the 
       // result of the request. 
      } 
     } 
     if (ContextCompat.checkSelfPermission(this, 
       Manifest.permission.ACCESS_FINE_LOCATION) 
       == PackageManager.PERMISSION_GRANTED) { 
      mMap.setMyLocationEnabled(true); 
      LocationManager initialLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
      Criteria criteria = new Criteria(); 
      String initialProvider = initialLocationManager.getBestProvider(criteria, true); 
      Location initialLocation = initialLocationManager.getLastKnownLocation(initialProvider); 
      mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); 
      double initialLatitude = initialLocation.getLatitude(); 
      double initialLongitude = initialLocation.getLongitude(); 
      LatLng initialLatLng = new LatLng(initialLatitude, initialLongitude); 
      mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(initialLatLng, 14.9f)); 
      //mMap.setOnInfoWindowClickListener(this); 
      mClusterManager = new ClusterManager<ClusterRequest>(getApplicationContext(), mMap); 
      mMap.setOnCameraChangeListener(mClusterManager); 
      mMap.setOnMarkerClickListener(mClusterManager); 
     } 
    } 

    public void onButtonClick(View view){ 
     //do something when button is clicked. 
     final Dialog dialog = new Dialog(this); 
     dialog.setContentView(R.layout.add_place); 
     dialog.setTitle("Add Place"); 

     Button btnLogin = (Button) dialog.findViewById(R.id.addPlacebtnSubmit); 
     Button btnCancel = (Button) dialog.findViewById(R.id.btnCancel); 
     final EditText txtUsername = (EditText)dialog.findViewById(R.id.txtStopName); 

     // Attached listener for add place GUI button 
     btnLogin.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       String stopName = txtUsername.getText().toString(); 
       if(stopName.length() > 4){ 
        // Here, thisActivity is the current activity 
        if (ContextCompat.checkSelfPermission(MapsActivity.this, 
          android.Manifest.permission.ACCESS_FINE_LOCATION) 
          != PackageManager.PERMISSION_GRANTED) { 

         // Should we show an explanation? 
         if (ActivityCompat.shouldShowRequestPermissionRationale(MapsActivity.this, 
           android.Manifest.permission.ACCESS_FINE_LOCATION)) { 

          // Show an expanation to the user *asynchronously* -- don't block 
          // this thread waiting for the user's response! After the user 
          // sees the explanation, try again to request the permission. 

         } else { 

          // No explanation needed, we can request the permission. 

          ActivityCompat.requestPermissions(MapsActivity.this, 
            new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 
            MY_PERMISSION_ACCESS_FINE_LOCATION); 

          // MY_PERMISSION_ACCESS_FINE_LOCATION is an 
          // app-defined int constant. The callback method gets the 
          // result of the request. 
         } 
        } 
        LocationManager currentLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
        Criteria currentCriteria = new Criteria(); 
        String currentProvider = currentLocationManager.getBestProvider(currentCriteria, true); 
        Location currentLocation = currentLocationManager.getLastKnownLocation(currentProvider); 
        double currentLatitude = currentLocation.getLatitude(); 
        double currentLongitude = currentLocation.getLongitude(); 
        LatLng currentLatLng = new LatLng(currentLatitude, currentLongitude); 

        ClusterRequest testCluster = new ClusterRequest(currentLatitude, currentLongitude); 
        mClusterManager.addItem(testCluster); 
        mClusterManager.setRenderer(new MapIconRender(getApplicationContext(), mMap, mClusterManager)); 

        dialog.dismiss(); 

       } 
       else{ 
        txtUsername.setError("Stop name must be at least 5 characters long."); 
       } 
      } 
     }); 
} 

MapIconRender.java

public class MapIconRender extends DefaultClusterRenderer<ClusterRequest> { 

     public MapIconRender(Context context, GoogleMap map, 
          ClusterManager<ClusterRequest> clusterManager) { 
      super(context, map, clusterManager); 
     } 

      @Override 
      protected void onBeforeClusterItemRendered (ClusterRequest item, MarkerOptions 
      markerOptions){ 
       markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_outside_azure)); 
       markerOptions.snippet("Status: "); 
       markerOptions.title(stopName); //<------ THIS IS WHERE I WANT THE STOP NAME TO BE WHAT THE USER ENTERED. 
       super.onBeforeClusterItemRendered(item, markerOptions); 
      } 
} 

add_place.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_height="match_parent" 
    android:paddingLeft="10dp" android:paddingRight="10dp" 
    android:background="#fff" android:layout_width="300dp" 
    android:paddingTop="10dp"> 
    <View 
     android:id="@+id/HorizontalLine" 
     android:layout_width="match_parent" 
     android:layout_height="1dip" 
     android:background="#aaa" /> 
    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textAppearance="?android:attr/textAppearanceMedium" 
     android:text="Name:" 
     android:paddingTop="20dp" 
     android:id="@+id/name" /> 
    <EditText android:layout_height="wrap_content" 
     android:id="@+id/txtStopName" 
     android:maxLength="100" 
     android:singleLine="true" 
     android:hint="Name of this stop (5-100 characters)" 
     android:layout_width="match_parent"> 
     <requestFocus></requestFocus> 
    </EditText> 
    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textAppearance="?android:attr/textAppearanceMedium" 
     android:text="Type:" 
     android:paddingTop="20dp" 
     android:layout_marginBottom="10dp" 
     android:id="@+id/type" /> 

    <Spinner 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:id="@+id/spinner" 
     android:entries="@array/type_arrays" 
     android:prompt="@string/type_prompt" 
     android:layout_marginBottom="10dp"/> 
    <View 
     android:id="@+id/HorizontalLine2" 
     android:layout_width="match_parent" 
     android:layout_height="1dip" 
     android:background="#aaa" /> 
    <LinearLayout android:layout_width="match_parent" 
     android:layout_height="wrap_content" android:id="@+id/linearLayout1" 
     android:paddingTop="5dp"> 

     <Button android:layout_width="wrap_content" 
      android:layout_height="wrap_content" android:layout_weight="0.5" 
      android:id="@+id/btnCancel" android:text="Cancel" 
      android:onClick="addPlaceCancel"/> 
     <Button android:layout_width="wrap_content" 
      android:layout_height="wrap_content" android:layout_weight="0.5" 
      android:id="@+id/addPlacebtnSubmit" android:text="Submit" 
      android:onClick="addPlaceSubmit" 
      android:layout_marginBottom="10dp"/> 
    </LinearLayout> 
</LinearLayout> 

ClusterRequest.java

public class ClusterRequest implements ClusterItem { 
private final LatLng mPosition; 

public ClusterRequest(double lat, double lng) { 
    mPosition = new LatLng(lat, lng); 
} 

@Override 
public LatLng getPosition() { 
    return mPosition; 
    } 
} 

답변

0

@SuhyeonLee이 당신이 무엇을 의미하는지 경우 (알려 주시기 바랍니다)하지만 난에 대한 발표 구글 데모에서 놀라 울 정도로 답을 찾았어요 사용자 정의 클러스터 데모. 내가 배운 것을 얻는다.
mClusterManager.setRenderer(new MapIconRender(getApplicationContext(), mMap, mClusterManager));

를 통해 MapIconRender.java 클래스를 호출 할 때 ClusterRequest 클래스의 변수는 여기에 MapIconRender에 액세스 할 수 있습니다 어떤 의미 MapIconRender.java 클래스

protected void onBeforeClusterItemRendered (ClusterRequest item, MarkerOptions 
      markerOptions) 

이 메소드를 실행한다. Java 클래스이며 (item.variableName)을 통해 액세스 할 수 있습니다. 나는 ClusterRequest 파일에 대한 코드를 게시하지 않아 사과드립니다. 필자는 그것이 필요하다고 생각하지 않았습니다. 아프 다시 가서 원래의 질문에 그 발췌 문장을 추가하십시오.다음과 같이

어쨌든 내가 추가하는 데 필요한 새로운 코드이었다 :
ClusterRequest testCluster = new ClusterRequest(currentLatitude, currentLongitude, stopName); //stopName was added here.

그리고에 : 나는 ClusterRequest 클래스를 통해 마커의 이름 (또는 마커의 제목)을 통과하는 데 필요한 MapsActivity 클래스에서
ClusterRequest 클래스는 내가 통해 마커 이름의 "전역 변수"(일명 stopName)를 추가 할 필요가 :

public class ClusterRequest implements ClusterItem { 
private final LatLng mPosition; 
public final String stopName; //Add a "global variable" here so it can be accessible in the MapIconRender class. 

public ClusterRequest(double lat, double lng, String _stopName) { 
    mPosition = new LatLng(lat, lng); 
    stopName = _stopName; 
} 

@Override 
public LatLng getPosition() { 
    return mPosition; 
    } 
} 



그리고 마지막으로 내 MapIconRender.java 클래스에서 나는 광고 수 D를 통해 마커의 제목 이름 :

public class MapIconRender extends DefaultClusterRenderer<ClusterRequest> { 

     public MapIconRender(Context context, GoogleMap map, 
          ClusterManager<ClusterRequest> clusterManager) { 
      super(context, map, clusterManager); 
     } 

      @Override 
      protected void onBeforeClusterItemRendered (ClusterRequest item, MarkerOptions 
      markerOptions){ 
       markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_outside_azure)); 
       markerOptions.snippet("Status: "); 
       markerOptions.title("Title: " + item.stopName); //Now we can access the title of the marker by calling item.variableName 
       super.onBeforeClusterItemRendered(item, markerOptions); 
      } 
} 

임 여기 멍청한 놈 질문에 대해 정말 미안하지만이 내가 그랬던 것처럼 것을 누군가가 같은 질문을 할 수 있습니다 도움이되기를 바랍니다 귀하의 답변 주셔서 감사합니다! "그래서"커뮤니티는 굉장합니다!

0

onClusterItemRendered() 방법을 무시할 수 없습니까?

나는 당신이 어떤 클래스 전역 변수 문자열에 onBeforeClusterItemRendered()에 마커 이름을 저장하고, Marker.setTitle(yourSavedTitle); 또는 뭔가 onClusterItemRendered()에 마커 이름을 설정할 수 있다고 생각합니다. 이 같은


뭔가 : 확실하지

public class MapIconRender extends DefaultClusterRenderer<ClusterRequest> { 
    private String mMarkerTitle; 

    public MapIconRender(Context context, GoogleMap map, 
         ClusterManager<ClusterRequest> clusterManager) { 
     super(context, map, clusterManager); 
    } 

     @Override 
     protected void onBeforeClusterItemRendered (ClusterRequest item, MarkerOptions 
     markerOptions){ 
      markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_outside_azure)); 
      markerOptions.snippet("Status: "); 
      markerOptions.title(stopName); //<------ THIS IS WHERE I WANT THE STOP NAME TO BE WHAT THE USER ENTERED. 
      mMarkerTitle = stopName; 
      super.onBeforeClusterItemRendered(item, markerOptions); 
     } 

     @Override 
     protected void onClusterItemRendered (ClusterRequest item, Marker marker){ 
      marker.setTitle(mMarkerTitle); 
     } 
} 
+0

안녕하세요, 당신의 말에 무슨 일이 일어나고 있는지 잘 모르시겠습니까? 만약 이걸 올바르게 생각하면 내 문제를 해결할 수 없었을 것입니다 (나는 도전적으로 여기에서 잘못 될 수 있습니다). 하지만 나는 여전히 add_place.xml에서 사용자의 입력에서 제목 이름을 가져 오지 않았다고 생각합니다. 클래스의 로컬 변수 일 뿐이며 값에 대한 XML을 제공하지 않습니다. 다시 나는 틀릴 수있다. 그러나 당신이 예제를 제공한다면 나는 당신의 설명을 더 많이 또는 덜 알 것이다. 응답에 노력을 많이 기울여 줘서 고맙습니다! – rapid3642

관련 문제