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