Android-如何为ScrollView项生成onClick代码?

问题描述 投票:0回答:1

我有一个可滚动的布局,可以垂直显示图像:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".chatActivity">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="2dp"
        android:layout_marginRight="2dp">

        <LinearLayout
            android:id="@+id/imageGallery"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical" />
    </ScrollView>
</RelativeLayout>

这是我在代码中生成视图的方式:

    LinearLayout imageGallery;
    File[] fList = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        imageGallery = (LinearLayout) findViewById(R.id.imageGallery);
        addImagesToTheGallery();
}

    private void addImagesToTheGallery() {

        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        fList = path.listFiles();
        if(fList!=null)
        {
            int len = fList.length;
            for(int i=0; i<len; i++)
            {
                imageGallery.addView(getImageView(i));
            }
        }
    }

    private View getImageView(int image) {
        ImageView imageView = new ImageView(getApplicationContext());
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        lp.setMargins(0, 0, 10, 0);
        imageView.setLayoutParams(lp);
        Bitmap bitmap = BitmapFactory.decodeFile(fList[image].getAbsolutePath());
        imageView.setImageBitmap(bitmap);
        return imageView;
    }

现在,我想为每个图像添加一个onClick事件。当有人单击图像时,我想显示一些消息。我该怎么办?

android android-linearlayout android-scrollview
1个回答
0
投票

在CLickListener上设置“ imageView”。

private View getImageView(int image) {
    ImageView imageView = new ImageView(getApplicationContext());
    LinearLayout.LayoutParams lp = new 
    LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 
    LinearLayout.LayoutParams.WRAP_CONTENT);
    lp.setMargins(0, 0, 10, 0);
    imageView.setLayoutParams(lp);
    Bitmap bitmap = BitmapFactory.decodeFile(fList[image].getAbsolutePath());
    imageView.setImageBitmap(bitmap);
    imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO do something
        }
    }); 
    return imageView;
}
© www.soinside.com 2019 - 2024. All rights reserved.