单击 GridView 中的项目时更改图像

发布于 2024-11-28 12:05:36 字数 6170 浏览 1 评论 0原文

我有一个包含 9 个项目的 GridView。我想做的是当我单击一个项目时,它的图标会发生变化。我这样做的方式返回

java.lang.ClassCastException: android.widget.LinearLayout

我必须的类:

MainLayout.java

public class MainLayout extends Activity implements OnItemClickListener
{   

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.mainlayout);

        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title);      

         final ImageButton btn=(ImageButton)findViewById(R.id.logoimagebutton);
         btn.setBackgroundColor(Color.TRANSPARENT);

         btn.setOnTouchListener(new OnTouchListener() {

                public boolean onTouch(View v, MotionEvent event) {
                    if (event.getAction() == MotionEvent.ACTION_DOWN ) {
                        btn.setImageResource(R.drawable.logoselected);
                        Toast.makeText(getApplicationContext(), "Clicked", Toast.LENGTH_SHORT).show();
                        //return true;
                    }else if (event.getAction() == MotionEvent.ACTION_UP) {
                        btn.setImageResource(R.drawable.logo);
                    }

                    return false;
                }
            });

        final GridView gridview = (GridView) findViewById(R.id.gridview);
        gridview.setAdapter(new ImageAdapter(this));            

        gridview.setOnItemClickListener(new OnItemClickListener()
        {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id)
            {                   
                ImageView imageView = (ImageView) v;
                imageView.setImageResource(ImageAdapter.mThumbSelected[position]);
            }
        });   
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
    {
        // TODO Auto-generated method stub

    }

}

ImageAdapter.java

public class ImageAdapter extends BaseAdapter
{

    private Context mContext;

    public static Integer[] mThumbIds = 
    {
            //a collection of images
    };

    public static Integer[] mThumbSelected = 
    {
            //a collection of images
    };

    private String[] mLabelsIds = {//a collection of strings};

    public ImageAdapter(Context c)
    {
        // TODO Auto-generated constructor stub
        mContext = c;
    }

    @Override
    public int getCount()
    {
        // TODO Auto-generated method stub
        return mThumbIds.length;
    }

    @Override
    public Object getItem(int arg0)
    {
        // TODO Auto-generated method stub
        return mThumbIds[arg0];
    }

    @Override
    public long getItemId(int arg0)
    {
        // TODO Auto-generated method stub
        return arg0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {       
        View grid;

        if (convertView == null)
        {
            grid = new View(mContext);
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            grid = inflater.inflate(R.layout.menugrid, parent, false);
        } else
        {
            grid = (View) convertView;
        }

        ImageView imageView = (ImageView) grid.findViewById(R.id.imageicon);
        TextView textView = (TextView) grid.findViewById(R.id.imagelabel);
        imageView.setImageResource(mThumbIds[position]);
        textView.setText(mLabelsIds[position]);

        return grid;
    }
}

这是我的两个 xml 文件:

menugrid.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:orientation="vertical">

     <ImageView
      android:id="@+id/imageicon"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      />
     <TextView
      android:id="@+id/imagelabel"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"     
      android:textColor="#000000"
      android:textSize="16px"
      android:gravity="center_horizontal"/>
</LinearLayout>

ma​​inlayout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainlayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" 
    android:orientation="vertical"
    android:background="@drawable/background">

    <LinearLayout
        android:id="@+id/holdlogo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"    
        android:orientation="horizontal"                    
        android:background="@drawable/title_background">

        <ImageButton
            android:id="@+id/logoimagebutton"
            android:scaleType="center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"    
            android:layout_gravity="center_vertical"    
            android:src="@drawable/logo"
            >
        </ImageButton>

    </LinearLayout>


    <GridView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/gridview"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:numColumns="auto_fit"
    android:layout_marginTop="10px"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:columnWidth="90dp"
    android:stretchMode="columnWidth"
    android:gravity="center"
/>  
</LinearLayout>

谁能告诉我我的代码有什么问题吗?或者如何在按下某个项目时更改其图像?我认为 onTouchListener 更有效,因为它有事件,所以当 event.getAction() == MotionEvent.ACTION_DOWN 时,我显示图像,当 event.getAction() 时,我显示图像== MotionEvent.ACTION_UP 我显示原始图标。

提前致谢。

I have a GridView with 9 items. What I'm trying to do is when I click an item, its icon changes. The way I'm doing it returns

java.lang.ClassCastException: android.widget.LinearLayout

I have to classes:

MainLayout.java

public class MainLayout extends Activity implements OnItemClickListener
{   

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.mainlayout);

        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title);      

         final ImageButton btn=(ImageButton)findViewById(R.id.logoimagebutton);
         btn.setBackgroundColor(Color.TRANSPARENT);

         btn.setOnTouchListener(new OnTouchListener() {

                public boolean onTouch(View v, MotionEvent event) {
                    if (event.getAction() == MotionEvent.ACTION_DOWN ) {
                        btn.setImageResource(R.drawable.logoselected);
                        Toast.makeText(getApplicationContext(), "Clicked", Toast.LENGTH_SHORT).show();
                        //return true;
                    }else if (event.getAction() == MotionEvent.ACTION_UP) {
                        btn.setImageResource(R.drawable.logo);
                    }

                    return false;
                }
            });

        final GridView gridview = (GridView) findViewById(R.id.gridview);
        gridview.setAdapter(new ImageAdapter(this));            

        gridview.setOnItemClickListener(new OnItemClickListener()
        {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id)
            {                   
                ImageView imageView = (ImageView) v;
                imageView.setImageResource(ImageAdapter.mThumbSelected[position]);
            }
        });   
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
    {
        // TODO Auto-generated method stub

    }

}

ImageAdapter.java

public class ImageAdapter extends BaseAdapter
{

    private Context mContext;

    public static Integer[] mThumbIds = 
    {
            //a collection of images
    };

    public static Integer[] mThumbSelected = 
    {
            //a collection of images
    };

    private String[] mLabelsIds = {//a collection of strings};

    public ImageAdapter(Context c)
    {
        // TODO Auto-generated constructor stub
        mContext = c;
    }

    @Override
    public int getCount()
    {
        // TODO Auto-generated method stub
        return mThumbIds.length;
    }

    @Override
    public Object getItem(int arg0)
    {
        // TODO Auto-generated method stub
        return mThumbIds[arg0];
    }

    @Override
    public long getItemId(int arg0)
    {
        // TODO Auto-generated method stub
        return arg0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {       
        View grid;

        if (convertView == null)
        {
            grid = new View(mContext);
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            grid = inflater.inflate(R.layout.menugrid, parent, false);
        } else
        {
            grid = (View) convertView;
        }

        ImageView imageView = (ImageView) grid.findViewById(R.id.imageicon);
        TextView textView = (TextView) grid.findViewById(R.id.imagelabel);
        imageView.setImageResource(mThumbIds[position]);
        textView.setText(mLabelsIds[position]);

        return grid;
    }
}

Here is my two xml files:

menugrid.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:orientation="vertical">

     <ImageView
      android:id="@+id/imageicon"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      />
     <TextView
      android:id="@+id/imagelabel"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"     
      android:textColor="#000000"
      android:textSize="16px"
      android:gravity="center_horizontal"/>
</LinearLayout>

mainlayout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainlayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" 
    android:orientation="vertical"
    android:background="@drawable/background">

    <LinearLayout
        android:id="@+id/holdlogo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"    
        android:orientation="horizontal"                    
        android:background="@drawable/title_background">

        <ImageButton
            android:id="@+id/logoimagebutton"
            android:scaleType="center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"    
            android:layout_gravity="center_vertical"    
            android:src="@drawable/logo"
            >
        </ImageButton>

    </LinearLayout>


    <GridView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/gridview"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:numColumns="auto_fit"
    android:layout_marginTop="10px"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:columnWidth="90dp"
    android:stretchMode="columnWidth"
    android:gravity="center"
/>  
</LinearLayout>

Can anyone tell me what is wrong in my code? Or How to change the image of an item when pressing it? I think onTouchListener is more efficient, due to the fact that it has the event, so when event.getAction() == MotionEvent.ACTION_DOWN I show the image and when event.getAction() == MotionEvent.ACTION_UP I show the original icon.

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

甜柠檬 2024-12-05 12:05:36

我猜你在这里收到了ClassCastException:

   public void onItemClick(AdapterView<?> parent, View v, int position, long id)
        {                   
            ImageView imageView = (ImageView) v;
            imageView.setImageResource(ImageAdapter.mThumbSelected[position]);
        }

发送的View实际上是ImageView所在的LinearLayout。你需要使用int位置获取项目,然后根据你的需要操作它,或者获取LinearLayout 内的 ImageView,这是您的网格项布局。

I guess you reveice the ClassCastException here:

   public void onItemClick(AdapterView<?> parent, View v, int position, long id)
        {                   
            ImageView imageView = (ImageView) v;
            imageView.setImageResource(ImageAdapter.mThumbSelected[position]);
        }

The View sent is actually the LinearLayout in which the ImageView resides in. You need to get the item using the int position and then manipulate it to your needs, or get the ImageView inside the LinearLayout, which is your Grid Item Layout.

迷鸟归林 2024-12-05 12:05:36

如果您使用 ViewHolder 类,您不仅可以优化网格视图,还可以从 OnItemClickListener 更轻松地访问图像视图。您在 ImageAdapter 中需要类似的内容:

class ViewHolder {
    ImageView img;
    TextView lbl;
}

然后将 getView 修改为如下所示:

public View getView(int position, View convertView, ViewGroup parent)
{       

    ViewHolder holder;
    if (convertView == null)
    {

        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.menugrid, parent, false);
        holder = new ViewHolder();
        holder.img = (ImageView) convertView.findViewById(R.id.imageicon);
        holder.lbl = (TextView) convertView.findViewById(R.id.imagelaberl);
        convertView.setTag(holder);
    } else
    {
        holder = (ViewHolder) convertView.getTag();
    }

    ImageView imageView = holder.img;
    TextView textView = holder.lbl;
    imageView.setImageResource(mThumbIds[position]);
    textView.setText(mLabelsIds[position]);

    return convertView;
}

现在在您的 OnItemClickListener 中,您可以像这样访问图像视图:

 public void onItemClick(AdapterView<?> parent, View v, int position, long id)
    {                   
        ImageView imageView = ((ViewHolder) v.getTag()).img;
        imageView.setImageResource(ImageAdapter.mThumbSelected[position]);
    }

这可以防止您经常调用 findViewById ,这将提高性能,因为这是一项昂贵的操作。

If you use a ViewHolder class you can not only optimize your grid view, but would be able to access the imageview easier from your OnItemClickListener. You need something like this in your ImageAdapter:

class ViewHolder {
    ImageView img;
    TextView lbl;
}

Then modify your getView to be like this:

public View getView(int position, View convertView, ViewGroup parent)
{       

    ViewHolder holder;
    if (convertView == null)
    {

        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.menugrid, parent, false);
        holder = new ViewHolder();
        holder.img = (ImageView) convertView.findViewById(R.id.imageicon);
        holder.lbl = (TextView) convertView.findViewById(R.id.imagelaberl);
        convertView.setTag(holder);
    } else
    {
        holder = (ViewHolder) convertView.getTag();
    }

    ImageView imageView = holder.img;
    TextView textView = holder.lbl;
    imageView.setImageResource(mThumbIds[position]);
    textView.setText(mLabelsIds[position]);

    return convertView;
}

Now in your OnItemClickListener you can access your image view like this:

 public void onItemClick(AdapterView<?> parent, View v, int position, long id)
    {                   
        ImageView imageView = ((ViewHolder) v.getTag()).img;
        imageView.setImageResource(ImageAdapter.mThumbSelected[position]);
    }

This prevents you from having to call findViewById as often, and that will improve performance since it is an expensive operation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文