如何从另一个类访问对象(例如ArrayList)?

时间:2011-12-07 22:37:15

标签: java android class object android-activity

我正在寻找一种允许我从另一个类访问对象的方法; 这两个类都在同一个Android活动中 - OpenStreeMapActivity.java。我有:

ItemizedOverlay.java - 包含我想要访问和修改的对象:

private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();

BalloonOverlayView.java - 我想要访问对象mOverlays的地方:

    protected void setupView(final Context context, final ViewGroup parent) {

    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = inflater.inflate(R.layout.balloon_overlay, parent);
    title = (TextView) v.findViewById(R.id.balloon_item_title);
    snippet = (TextView) v.findViewById(R.id.balloon_item_snippet);

    // Get ballon_close button and register its listener:
    ImageView close = (ImageView) v.findViewById(R.id.balloon_close);
    close.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            parent.setVisibility(GONE); 

            Intent intent = new Intent( );
            intent.setClassName( "org.example.openstreetmap", "org.example.openstreetmap.UpdateEntityActivity" );
            v.getContext().startActivity(intent);

            //HERE I return from UpdateOverlayActivity.java and is where I want to modify *mOverlays*.
        }
    });

} 

编辑:我发现我回到这里是不正确的。

2 个答案:

答案 0 :(得分:3)

在ItemizedOverlay中,创建一个提供对象的方法。

public List<OverlayItem> getOverlays() {
  return this.mOverlays;
}

如果您使用List,那么更好,如果将来您想要更改实现,它不会影响其他地方的代码。

答案 1 :(得分:1)

您可以让BalloonOverlayView以这种方式保持对OverlayItem对象列表的引用:

public class BalloonOverlayView{
 List<OverlayItem> items = null;
 public BalloonOverlayView(List<OverlayItem> items){
    this.items = items;
 }
 // Now you can use the ItemizedOverlay class from within this class as you wish
 public void addItem(OverlayItem item){
    items.add(item);
 }
 public void removeItem(OverlayItem item){
    item.remove(item);
 }
}