如何使用ArrayAdapter从ArrayList中的ListView中显示项目(图像的路径)?我的代码不起作用-它不打印图像路径列表。
public class MainActivity extends Activity {
ImageView imageView;
Button button;
private static final int PICK_IMAGE = 100;
Uri imageUri;
ArrayList<String> urllist = new ArrayList<>();
ListView list;
TextView tv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView)findViewById(R.id.imageView);
button = (Button)findViewById(R.id.buttonLoadPicture);
list = (ListView) findViewById(R.id.list);
//tv=(TextView) findViewById(R.id.tv);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, urllist);
list.setAdapter(adapter);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openGallery();
}
});
}
private void openGallery() {
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE){
imageUri = data.getData();
imageView.setImageURI(imageUri);
String name = data.getData().getPath();
urllist.add(name); //here I add each path to list
//tv.setText(TextUtils.concat(tv.getText(), " ", name));
Toast.makeText(this, name, Toast.LENGTH_SHORT).show();
}
}
}
在更新时urllist,还需要通知适配器。为此,请改成您adapter的字段。
然后,当您向其中添加项目时urllist,别忘了打电话adapter.notifyDataSetChanged()。
ArrayList<String> urllist = new ArrayList<>();
// Make adapter a field
ArrayAdapter<String> adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ...
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, urllist);
list.setAdapter(adapter);
// ...
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE){
// ...
urllist.add(name); //here I add each path to list
// Notify the adapter
adapter.notifyDataSetChanged();
}
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。