0

我想添加一個搜索欄到android地圖。 該地圖被添加爲項目的一個片段。該錯誤似乎由this引入。任何幫助表示讚賞。提前致謝。添加搜索按鈕到地圖

public class Maps extends Fragment { 
    //Initial code 

    public void onSearch(View view) { 
     EditText location_tf = (EditText) getView().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()); 
    googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng)); 
} 

XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical"> 

    <LinearLayout android:layout_width="wrap_content" 
     android:layout_height="wrap_content"> 
     <EditText android:layout_width="287dp" 
      android:layout_height="wrap_content" 
      android:id="@+id/TFaddress"/> 
     <Button style="?android:attr/buttonStyleSmall" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Search" 
      android:id="@+id/button" 
      android:layout_gravity="right" 
      android:onClick="onSearch" /> 
     <com.google.android.gms.maps.MapView 
      android:id="@+id/map" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent"/> 
    </LinearLayout> 

錯誤:

Error:(83, 46) error: incompatible types: MAPS cannot be converted to Context 
Note: Some input files use or override a deprecated API. 
Note: Recompile with -Xlint:deprecation for details. 
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output.  
Error:Execution failed for task ':app:compileDebugJava'. Compilation failed; see the compiler error output for details. 

回答

0

the documentation,將Geocoder構造函數需要一個Context,不是Fragment,所以這行

Geocoder geocoder = new Geocoder(this); 

應該

Geocoder geocoder = new Geocoder(getActivity()); 

此外,考慮到你可能想在你的if語句添加括號帳戶:

if (location != null || !location.equals("")) 
    Geocoder geocoder = new Geocoder(this); 

    try { 
     addressList = geocoder.getFromLocationName(location, 1); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 
+0

感謝您的幫助。但是,在糾正我的代碼後,當我嘗試運行它時,TomCat:java.lang.IllegalStateException:在視圖類android.support上定義的android:onClick屬性的父代或祖代上下文中找不到方法onSearch(View)。 v7.widget.AppCompatButton id爲'button' – Chid

+0

試着讓你的'onSearch(View view)'public:'public onSearch(View view)' – antonio

+0

試過了。沒有運氣。 – Chid