简体   繁体   中英

How can I access an object (e.g. ArrayList) from another class?

I am looking for a way that allows me access an object from another class; both classes are within the same Android activity - OpenStreeMapActivity.java. I have:

ItemizedOverlay.java - Contains the object I want to access and modify:

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

BalloonOverlayView.java - Is where I want to access the object 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*.
        }
    });

} 

Edit: I figured out that it is not true that I return to //HERE.

In ItemizedOverlay, create a method that provides the object.

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

Better if you use the List so, if in the future you want to change the implementation it does not affect your code elsewhere.

You can make the BalloonOverlayView hold a reference to a list of OverlayItem object this way:

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);
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM