2011-02-10 164 views
2

大家好我正在嘗試使用GridView顯示一些圖像。然而,當我導入android.widget.AdapterView.OnItemClickListener時,我得到一個錯誤,說主不能被解析或不是字段。我的代碼如下:在GridView中顯示圖片

import import android.app.Activity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.GridView; 
import android.widget.Toast; 
import android.widget.AdapterView.OnItemClickListener; 
//Error here: main cannot be resolved or is not field 

public class MainActivity extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

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

     gridview.setOnItemClickListener(new OnItemClickListener() { 
      public void onItemClick(AdapterView<?> parent, View v, int position, long id) { 
       Toast.makeText(MainActivity.this, "" + position, Toast.LENGTH_SHORT).show(); 
      } 
     }); 
    } 
} 

package com.newapp; 

import android.content.Context; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.BaseAdapter; 
import android.widget.GridView; 
import android.widget.ImageView; 

public class ImageAdapter extends BaseAdapter{ 

    private Context mContext; 

public ImageAdapter(Context c) { 
    mContext = c; 
} 

public int getCount() { 
    return mThumbIds.length; 
} 

public Object getItem(int position) { 
    return null; 
} 

public long getItemId(int position) { 
    return 0; 
} 

// create a new ImageView for each item referenced by the Adapter 
public View getView(int position, View convertView, ViewGroup parent) { 
    ImageView imageView; 
    if (convertView == null) { // if it's not recycled, initialize some attributes 
     imageView = new ImageView(mContext); 
     imageView.setLayoutParams(new GridView.LayoutParams(85, 85)); 
     imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); 
     imageView.setPadding(8, 8, 8, 8); 
    } else { 
     imageView = (ImageView) convertView; 
    } 

    imageView.setImageResource(mThumbIds[position]); 
    return imageView; 
} 

// references to our images 
private Integer[] mThumbIds = { 

     R.drawable.sample_0, R.drawable.sample_1, 
     R.drawable.sample_2, R.drawable.sample_3, 
     R.drawable.sample_4, R.drawable.sample_5, 
     R.drawable.sample_6, R.drawable.sample_7, 

    }; 
} 

有人可以告訴我爲什麼我得到這個錯誤嗎?任何幫助將不勝感激。謝謝

回答

0

這可能與導入無關,我猜它是抱怨這個:R.layout.main。這是您定義的佈局嗎?您需要導入正確的R文件,很可能是您的軟件包中生成的文件:com.newapp.R?

此外,我認爲在開始的額外導入是複製錯誤?

+0

是的,你是對的額外進口在開始是複製錯誤。非常感謝Mayra的幫助。這個答案幫了我很多。 – Engprof 2011-02-10 01:57:46