Har*_*elm 2 android adapter android-activity
我不确定从适配器到相应的Activity的最佳通信方式是什么.
我的活动有一个布局,上面有一个WebView和一个Gallery:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:orientation="vertical" >
<Gallery
android:id="@+id/gallery"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_width="fill_parent"
android:spacing="2dip" />
<WebView
android:id="@+id/webview"
android:layout_height="wrap_content"
android:layout_weight="5"
android:layout_width="fill_parent" />
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)
活动将图像数据加载到图库中:
public class MyActivity extends Activity {
private MyAdapter adapter;
private Container container;
private ArrayList<Container> containers = new ArrayList<Container>();
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<Container> fetchContainers() {
ArrayList<Container> containers = null;
...
return containers;
}
}
Run Code Online (Sandbox Code Playgroud)
单击其中一个图像应更改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<Container> 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<Container> containers) {
this.containers = containers;
this.context = context;
}
}
Run Code Online (Sandbox Code Playgroud)
现在我的问题是.如何通知活动有关已点击的图像并将一个对象传输到活动?
我的想法是使用BroadcastReceiver,但我不认为这是首选方式.我该怎么办?
提前谢谢了.
而是创建Imageview的单击侦听器,使用gallery的setOnItemClickListener
yourGallery.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3) {
system.out.println("position"+position);
}
});
Run Code Online (Sandbox Code Playgroud)