2016-05-24 2 views
0

Как я могу использовать этот метод для использования в классе фрагментов? Я не могу использовать этот метод во фрагменте (onCreate).onSearch метод внутри фрагмента

public void onSearch(View view) { 
     EditText location_tf = (EditText) findViewById(R.id.TFaddress); 
     String location = location_tf.getText().toString(); 
     List<Address> addressList = null; 
     if (location != null || !location.equals("")) { 
      Geocoder geocoder = new Geocoder(this); 
      try { 
       addressList = geocoder.getFromLocationName(location, 1); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
       Address address = addressList.get(0); 
      LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude()); 
      mMap.addMarker(new MarkerOptions().position(latLng).title("Marker")); 
      mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng)); 
      } 
    } 

Я не знаю, как включение в действие с помощью этого метода onSearch, макет готов получить метод, но не знаю, как вставить его в классе. Я пытаюсь вставить onSearch метод в этом коде:

public class FragmentC extends Fragment{ 
    MapView mMapView; 
    private GoogleMap googleMap; 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 
     // inflat and return the layout 
     View v = inflater.inflate(R.layout.frag4, container, 
       false); 
     mMapView = (MapView) v.findViewById(R.id.map); 
     mMapView.onCreate(savedInstanceState); 

     mMapView.onResume();// needed to get the map to display immediately 

     try { 
      MapsInitializer.initialize(getActivity().getApplicationContext()); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

     googleMap = mMapView.getMap(); 
     // latitude and longitude 
     double latitude = 17.385044; 
     double longitude = 78.486671; 

     // create marker 
     MarkerOptions marker = new MarkerOptions().position(
       new LatLng(latitude, longitude)).title("Hello Maps"); 

     // Changing marker icon 
     marker.icon(BitmapDescriptorFactory 
       .defaultMarker(BitmapDescriptorFactory.HUE_ROSE)); 

     // adding marker 
     googleMap.addMarker(marker); 
     CameraPosition cameraPosition = new CameraPosition.Builder() 
       .target(new LatLng(17.385044, 78.486671)).zoom(12).build(); 
     googleMap.animateCamera(CameraUpdateFactory 
       .newCameraPosition(cameraPosition)); 

     // Perform any camera updates here 
     return v; 
    } 

    @Override 
    public void onResume() { 
     super.onResume(); 
     mMapView.onResume(); 
    } 

    @Override 
    public void onPause() { 
     super.onPause(); 
     mMapView.onPause(); 
    } 

    @Override 
    public void onDestroy() { 
     super.onDestroyView(); 
     // Log.d(TAG, "onDestroyView"); 

     Fragment f = getActivity() 
       .getSupportFragmentManager().findFragmentById(R.id.map); 
     if (f != null) { 
      getActivity().getSupportFragmentManager() 
      .beginTransaction().remove(f).commit(); 
     } 
    } 

    @Override 
    public void onLowMemory() { 
     super.onLowMemory(); 
     mMapView.onLowMemory(); 
    } 
+1

Вы должны предоставить больше контекста, потому что кажется, что вы объявили это в вашей деятельности, но это не ясно, почему вы хотели бы это вызывается из вашего фрагмента, что вы делаете в своем фрагменте и что именно вы намереваетесь с этим. –

+1

Спасибо за помощь, я отредактировал описание, пожалуйста, посмотрите еще раз. @azetaguionbajo –

+0

Там я отредактировал ответ. Это должно сделать это. –

ответ

0

Предполагая, что mMapView такое же, как MMAP, и что Theres кнопка, которая запускает onSearch метод, вот как ваш фрагмент кода должен выглядеть следующим образом. Обратите внимание на onCreateView изменений и что метод onSearch не recieves на вид параметров:

private EditText mLocationEditText; 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    // inflat and return the layout 
    View v = inflater.inflate(R.layout.frag4, container, 
      false); 
    mMapView = (MapView) v.findViewById(R.id.map); 
    mMapView.onCreate(savedInstanceState); 
    mMapView.onResume();// needed to get the map to display immediately 

    // Obtain the EditText view reference first 
    mLocationEditText = (EditText) v.findViewById(R.id.TFaddress); 

    // Obtain the button that triggers the onSearch reference 
    mButtonThatTriggersSearch = (Button) v..findViewById(R.id.search_button_id); 
    // Set the onClickListener that should excecute when someome clicks the button 
    mButtonThatTriggersSearch.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      // Perform action on click 
      onSearch(); 
     } 
    }); 

    try { 
     MapsInitializer.initialize(getActivity().getApplicationContext()); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

    googleMap = mMapView.getMap(); 
    // latitude and longitude 
    double latitude = 17.385044; 
    double longitude = 78.486671; 

    // create marker 
    MarkerOptions marker = new MarkerOptions().position(
      new LatLng(latitude, longitude)).title("Hello Maps"); 

    // Changing marker icon 
    marker.icon(BitmapDescriptorFactory 
      .defaultMarker(BitmapDescriptorFactory.HUE_ROSE)); 

    // adding marker 
    googleMap.addMarker(marker); 
    CameraPosition cameraPosition = new CameraPosition.Builder() 
      .target(new LatLng(17.385044, 78.486671)).zoom(12).build(); 
    googleMap.animateCamera(CameraUpdateFactory 
      .newCameraPosition(cameraPosition)); 

    // Perform any camera updates here 
    return v; 
} 

private void onSearch() { 
    String location = mLocationEditText.getText().toString(); 
    List<Address> addressList = null; 
    if (location != null || !location.equals("")) { 
     Geocoder geocoder = new Geocoder(getActivity()); 
     try { 
      addressList = geocoder.getFromLocationName(location, 1); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     Address address = addressList.get(0); 
     LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude()); 
     mLocationEditText.addMarker(new MarkerOptions().position(latLng).title("Marker")); 
     mLocationEditText.animateCamera(CameraUpdateFactory.newLatLng(latLng)); 
    } 
} 
Смежные вопросы