如何使用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();
}
}
@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
Toast.makeText(this, name, Toast.LENGTH_SHORT).show();
// assign urllist to adapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, urllist);
list.setAdapter(adapter);
}
}