2012-11-11 34 views
5

我在我的MapActivity.java中創建一個OSMdroid mapview,我想添加按鈕&彈出窗口 - 我只知道這是如何在.xml中完成的,但因爲這個MapView沒有使用任何.xml我是不知道如何在我的java代碼中放置(圖像)按鈕。Mapview上的按鈕

@Override 
public void onCreate(final Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    // Setup base map 
    final RelativeLayout rl = new RelativeLayout(this); 

    CloudmadeUtil.retrieveCloudmadeKey(getApplicationContext()); 

    final MapView osmv = new MapView(this, 256); 

    myMapController = osmv.getController(); 

    rl.addView(osmv, new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, 
      LayoutParams.FILL_PARENT)); 
    osmv.setBuiltInZoomControls(true); 
    osmv.setMultiTouchControls(true); 

    myLocationoverlay = new MyLocationOverlay(this, osmv); 

//*snip* setup of map, mapcontrollers, tiles etc... 
    osmv.getOverlays().add(tilesOverlay); 
    osmv.getOverlays().add(myLocationoverlay); 

    this.setContentView(rl); 
} 

編輯: 我講的一個按鈕,像

<ImageButton 
    android:id="@+id/map_goto_location" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:src="@drawable/goto_location" 
    android:layout_alignParentRight="true" 
    android:layout_alignParentTop="true" 
    android:id="@+id/goto_location" /> 
+2

由於您將'MapView'添加到'RelativeLayout',因此只需將其他任何UI元素添加到相同的容器即可。只需確保在添加「MapView」後添加它們,以便將它們繪製在頂部。您可以在代碼中設置所有的UI元素,或者在xml中聲明它們並使用'LayoutInflater'來擴充它們。另外,不要忘記在創建/膨脹之後添加它們。 –

回答

4

由於MH的提示,我發現瞭如何將ImageButton的編程方式添加到我的代碼如下:

ImageButton goto_location = new ImageButton(this); 
    goto_location.setOnClickListener(new OnClickListener() 
    { 
     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      showMylocation(); 
     }   
    }); 

    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(40, 40); 
    params.rightMargin = 10; 
    params.topMargin = 10; 
    rl.addView(goto_location, params); 

如果任何人都可以提示我一些關於自定義按鈕和以編程方式添加UI元素的好教程/示例,我會非常高興。

+0

也可以在佈局XML中定義此按鈕。只需創建一個RelativeLayout並添加osmdroid MapView和你的按鈕。 – scai