当前位置:  开发笔记 > Android > 正文

如何在Adapter和Activity之间进行通信

如何解决《如何在Adapter和Activity之间进行通信》经验,为你挑选了1个好方法。

我不确定从适配器到相应的Activity的最佳通信方式是什么.

我的活动有一个布局,上面有一个WebView和一个Gallery:





           

    

活动将图像数据加载到图库中:

public class MyActivity extends Activity {

  private MyAdapter            adapter;
  private Container            container;
  private ArrayList containers = new ArrayList();
  private Gallery              gallery;
  private WebView              webView;

  @Override
  public void onCreate(Bundle bundle) {
    ...
    gallery = (Gallery) findViewById(R.id.gallery);
    webView = (WebView) findViewById(R.id.webview);

    containers = fetchContainers();
    doGallery();
  }

  private void doGallery() {
    adapter = new MyAdapter(this,
                            containers);
    gallery.setAdapter(adapter);
  }

  private ArrayList fetchContainers() {
    ArrayList containers = null;
    ...
    return containers;
  }
}

单击其中一个图像应更改webview的内容.这是带有OnClickListener的适配器:

public class MyAdapter extends BaseAdapter {

  private class MyOnClickListener implements OnClickListener {

    private Container container; 
    private Context   context; 

    public MyOnClickListener(Context context, Container container) {
      this.container = container;
      this.context = context;
    }

    public void onClick(View view) {
      //TODO: change contents of WebView
    }
  }

  private ArrayList containers;
  private Context              context;

  public View getView(final int position, final View contentView, final ViewGroup viewGroup) {
    ImageView imageView = new ImageView(context);
    Container container = containers.get(position);
    // get image data from image cache
    imageView.setOnClickListener(new MyOnClickListener(context, container));
    return imageView;
  }

  public MyAdapter(Context context, ArrayList containers) {
    this.containers = containers;
    this.context = context;
  }
}

现在我的问题是.如何通知活动有关已点击的图像并将一个对象传输到活动?

我的想法是使用BroadcastReceiver,但我不认为这是首选方式.我该怎么办?

提前谢谢了.



1> Mohammed Azh..:

而是创建Imageview的单击侦听器,使用gallery的setOnItemClickListener

 yourGallery.setOnItemClickListener(new OnItemClickListener() 
 {
     @Override
     public void onItemClick(AdapterView arg0, View arg1,int position, long arg3) {

         system.out.println("position"+position);               

     }
 });

推荐阅读
黄晓敏3023
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有