我编写了以下代码,但是我确定在onItemClick()方法中做错了什么
我的列表视图显示正确,当单击另一个活动时,我只想在新活动中显示图像
所以需要你们的帮助
主要活动
public class MainActivity extends ActionBarActivity {String[] days = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };int[] images = { R.drawable.ic_launcher, R.drawable.ic_launcher, R.drawable.ic_launcher, R.drawable.ic_launcher, R.drawable.ic_launcher, R.drawable.ic_launcher, R.drawable.ic_launcher };int[] images1 = { R.drawable.image01, R.drawable.image02, R.drawable.image03, R.drawable.image04, R.drawable.image05, R.drawable.image06, R.drawable.image07 };ListView lv;@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lv = (ListView) findViewById(R.id.listView1); ArjAdapter adapter = new ArjAdapter(getBaseContext(), days, images); lv.setAdapter(adapter); lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub File imgfile = new File(""); if (imgfile.exists()) { String myBitmap = imgfile.getAbsolutePath(); Intent intent = new Intent(MainActivity.this, ImageActivity.class); intent.setType("image/*"); intent.putExtra("img", "images1"); startActivity(intent); } } });
在上述方法中,我不确定文件对象内部应包含什么内容,我在某处看到了该方法,但不确定文件内部包含什么内容,因此请留空以咨询大家
ImageActivity,我要在其中显示图像
public class ImageActivity extends Activity {ImageView iv;@Overrideprotected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.images); Bitmap myBitmap = BitmapFactory.decodeFile(getIntent().getStringExtra( "img")); ImageView iv = (ImageView) findViewById(R.id.imageView2); iv.setImageBitmap(myBitmap);}
任何建议都欢迎
解决方法:
你应该这样写onListItemClick()
lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(MainActivity.this, ImageActivity.class); intent.putExtra("img", images1[position]); startActivity(intent); } });
ImageActivity.java
public class ImageActivity extends Activity { ImageView iv; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.images); ImageView iv = (ImageView) findViewById(R.id.imageView2); iv.setImageResource(getIntent().getIntExtra("img", 0)); }}
输出:
来源:https://www.icode9.com/content-4-506501.html联系客服