I want to design a listView such that when a user adds a photo, it will automatically update the listView with the name of the image and it's thumbnail. However my current attempts don't even render the image. Is it possible to dynamically set the ImageView for each cell of a listView and have it be updated when I add a new element to the Adapter?
XML for listView and add button:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".Photos"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="#+id/view_album_bar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<ListView android:layout_marginTop="?android:attr/actionBarSize"
android:id="#+id/photos_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:choiceMode="singleChoice"
android:listSelector="#android:color/darker_gray" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/add_photo_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="25dp"
android:layout_marginEnd="25dp"
android:clickable="true"
android:src="#drawable/plus"/>
</RelativeLayout>
Activity:
public class ViewAlbum extends AppCompatActivity {
public Album activeAlbum;
private ListView photoList;
private ArrayList<String> currentPhotos = new ArrayList<String>();
private ArrayAdapter<String> adapter;
private int currentSelected = -1;
public static final int PICK_IMAGE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_album);
final Context context = getApplicationContext();
Toolbar albumBar = findViewById(R.id.view_album_bar);
setSupportActionBar(albumBar);
photoList = findViewById(R.id.photos_list);
Bundle bundle = getIntent().getExtras();
String albumName = bundle.getString("album_name");
activeAlbum = Album.loadAlbum(this.getFilesDir().getPath()+"/"+albumName+".txt");
for(Photo photo: activeAlbum.photos){
ImageView thumbnail = findViewById(R.id.photo_thumbnail);
if(thumbnail == null){
System.out.println("why?");
//Don't understand why it is null, can't set image
}
currentPhotos.add(photo.name);
}
adapter = new ArrayAdapter<String>(this, R.layout.photo_cell,
R.id.photo_name,currentPhotos);
photoList.setAdapter(adapter);
photoList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
currentSelected = position;
}
});
FloatingActionButton addPhotoBtn = (FloatingActionButton)findViewById(R.id.add_photo_btn);
addPhotoBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == Activity.RESULT_OK
&& data != null && data.getData() != null) {
Uri uri = data.getData();
Photo newPhoto = new Photo("name", uri.getPath());
activeAlbum.photos.add(newPhoto);
activeAlbum.saveAlbum();
}
}
Each ListView Cell:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?android:attr/activatedBackgroundIndicator">
<LinearLayout android:id="#+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="3dip"
android:layout_alignParentLeft="true"
android:layout_marginRight="5dip">
<ImageView
android:id="#+id/photo_thumbnail"
android:layout_width="106dp"
android:layout_height="77dp" />
</LinearLayout>
<TextView
android:id="#+id/photo_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="25dp"
android:text="Album Name"
android:textColor="#0984e3"
android:textSize="25dip"
android:textStyle="bold"
android:typeface="sans" />
</RelativeLayout>
Firstly, I think album.photo is not the same array as the array you passed when you create the adapter (currentPhotos). So adding new Photo to album.photo does not reflect that item in the listView.
Secondly, as user dev points out, whenever you change the data you need to tell the adapter by adapter.notifyDataSetChanged(). However in your case, you always add to the end i think it is better to call adapter.notifyDataInserted(currentPhotos.size() - 1)
When you get result on OnActivityResult() add it to currentPhotos,
then call notifyDataSetChanged()
If you are working with images which are locally stored or on the web. Using a lib like implementation 'com.squareup.picasso:picasso:2.71828' is probably a good idea as it can handle image and URL based exception and had a catch of the data so that it is easier to open apps memory can be used minimally.
Related
I have a problem with onItemClick method in android.
I know other people have encountered such problems, found some references to their questions on SO, read about the answers provided and some other articles on the internet but it didn't help. Things seem a bit different in my case.
I have a listview of some objects for which I want to show details when they're clicked. But Awkwardly the listener is working fine for only the first object of the listview. The app keeps aborting when I click on other elements of the listview. I can't figure out what's going on.
As I was using the id to retrieve the object I tried changing the id by the position, which didn't work either.
Here is the code of the onCreate method in my activity (DrinkCategoryActivity)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drink_category);
ArrayAdapter<Drink> listAdapter = new ArrayAdapter<>(
this, android.R.layout.simple_list_item_1, Drink.drinks
);
ListView listDrinks = (ListView) findViewById(R.id.list_drinks);
listDrinks.setAdapter(listAdapter);
AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> listDrinks,
View itemView, int position, long id) {
Intent intent = new Intent(DrinkCategoryActivity.this, DrinkActivity.class);
intent.putExtra(DrinkActivity.EXTRA_DRINKID, (int) id);
startActivity(intent);
}
};
listDrinks.setOnItemClickListener(itemClickListener);
}
My DrinkActivity (the one that should show me the details of each Drink object when clicked in the listview) onCreate method code is shown below
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drink);
int drinkId = (int) getIntent().getExtras().get(EXTRA_DRINKID);
Drink drinkItem = Drink.drinks[drinkId];
ImageView image = (ImageView) findViewById(R.id.drink_image);
image.setImageResource(drinkItem.getImageResourceId());
TextView drink_name = (TextView) findViewById(R.id.drink_name);
drink_name.setText(drinkItem.getName());
TextView drink_description = (TextView) findViewById(R.id.drink_description);
drink_description.setText(drinkItem.getDescription());
TextView drink_price = (TextView) findViewById(R.id.drink_price);
String price = ""+drinkItem.getPrice();
drink_price.setText(price);
}
I don't know whether there is something wrong with the xml files so here they are :
activity_drink_category.xml goes below
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activities.DrinkCategoryActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
layout="#layout/customer_screen_toolbar_layout"/>
<ListView
android:layout_marginTop="10dp"
android:id="#+id/list_drinks"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</androidx.drawerlayout.widget.DrawerLayout>
And activity_drink.xml goes here
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".activities.DrinkActivity">
<include
layout="#layout/customer_screen_toolbar_layout"/>
<ImageView
android:id="#+id/drink_image"
android:layout_width="190dp"
android:layout_height="190dp" />
<TextView
android:id="#+id/drink_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/drink_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/drink_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:background="#EB8E13"
android:textColor="#color/white" />
</LinearLayout>
Any help will be valuable. Thanks in advance
You need to pass "Position" instead of "id" in Intent. As you describe above its works fine for the first position. Then you need to Use position
intent.putExtra(DrinkActivity.EXTRA_DRINKID, (int) position);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drink_category);
ArrayAdapter<Drink> listAdapter = new ArrayAdapter<>(
this, android.R.layout.simple_list_item_1, Drink.drinks
);
ListView listDrinks = (ListView) findViewById(R.id.list_drinks);
listDrinks.setAdapter(listAdapter);
AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> listDrinks,
View itemView, int position, long id) {
Intent intent = new Intent(DrinkCategoryActivity.this, DrinkActivity.class);
intent.putExtra(DrinkActivity.EXTRA_DRINKID, (int) position);
startActivity(intent);
}
};
listDrinks.setOnItemClickListener(itemClickListener);
}
I’m trying to implement a RecyclerView with horizontal scrolling, so I’m using this a LinearLayoutManager with horizontal orientation. The problem is that I’m populating the RecyclerView using 2 different types of items, with different heights. This is the layout I’m using for the item:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="10dp">
<LinearLayout
android:id="#+id/document_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#drawable/ic_rounded"
android:backgroundTint="#color/ms_black_ms_gray"
android:gravity="center"
android:layout_gravity="bottom"
android:padding="5dp"
android:paddingStart="15dp">
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/white"
android:textSize="13sp"
android:singleLine="true"
android:maxWidth="80dp"
tools:text="example_form"/>
<TextView
android:id="#+id/format"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/white"
android:textSize="13sp" />
…
</LinearLayout>
<android.support.v7.widget.CardView
android:id="#+id/image_view"
android:layout_width="120dp"
android:layout_height="80dp"
android:layout_gravity="bottom"
app:cardCornerRadius="25dp"
app:cardElevation="0dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/preview_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"/>
…
</RelativeLayout>
</android.support.v7.widget.CardView>
and this is the layout that contains the RecyclerView, which is basically like this:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingStart="14dp"
android:paddingEnd="14dp">
<ImageView
android:id="#+id/attach"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_gravity="bottom"
android:layout_marginBottom="19dp"
android:visibility="visible"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginBottom="10dp"
android:layout_marginTop="5dp"
android:padding="3dp"
android:foreground="#drawable/ic_rounded_stroke"
android:foregroundTint="#color/white">
<android.support.constraint.ConstraintLayout
android:id="#+id/chatEdit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/ic_rounded"
android:foreground="#drawable/ic_rounded_stroke"
android:padding="6dp"
android:visibility="visible">
<EditText
android:id="#+id/editText"
android:textSize="17sp"
android:textColor="#121212"
android:letterSpacing="-0.02"
android:lineSpacingExtra="0sp"
android:padding="10dp"
android:paddingStart="15dp"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:maxLines="5"
android:hint="#string/chat_hint"
android:inputType="textCapSentences|textMultiLine"
android:maxLength="2500"
android:background="#null"
app:layout_constraintRight_toLeftOf="#id/buttonsContainer"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/send"
android:layout_gravity="bottom"
android:visibility="visible"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:paddingBottom="10dp"
android:paddingTop="8dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textColor="#ffffff"
android:letterSpacing="-0.02"
android:gravity="center_horizontal"
android:text="#string/send"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
/>
<android.support.v7.widget.RecyclerView
android:id="#+id/filesList"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:paddingTop="5dp"
android:paddingEnd="5dp"
android:visibility="gone"
app:layout_constraintRight_toLeftOf="#id/send"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="#id/editText"
app:layout_constraintBottom_toBottomOf="parent"/>
</android.support.constraint.ConstraintLayout>
</LinearLayout>
</LinearLayout>
I’m using a single ViewHolder, I just change the visibility of the 2 child views.
The result I expect to get is this one:
But what I’m getting is this; the CardView being cut in half, using the height of the second type of item:
I saw this post, which is similar to my problem. It recommends using Google’s Flexbox. So, I tried to implement FlexboxLayoutManager:
FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(getContext());
layoutManager.setFlexDirection(FlexDirection.ROW);
layoutManager.setFlexWrap(FlexWrap.NOWRAP);
I’m using row direction and It is showing items on next lines if it does not fit in single line. So, I also added No_wrap. And now it is showing items in a single line but do not provide scrolling. Also in this case it tries to fit all items in a single line by decreasing width of items.
I also played with the flex box sample app, but I couldn’t get the result I want.
Is there a way I can achieve horizontal scrolling with the Flexbox integrated with RecyclerView? Or should I use a different approach?
Thanks
EDIT
Thanks for the tips and everything, but it is not solving it. So, I stripped down the code to bare minimum to reproduce this.
MainActivity:
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CODE = 1;
private RecyclerView recyclerView;
private FilesAdapter filesAdapter;
private List<File> filesList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
LinearLayoutManager filesLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(filesLayoutManager);
filesAdapter = new FilesAdapter(filesList);
recyclerView.setAdapter(filesAdapter);
ImageView attach = findViewById(R.id.attach);
attach.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(Intent.createChooser(intent,"Select Files"), REQUEST_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
try {
if (data != null) {
List<File> uriList = new ArrayList<>();
if (data.getClipData() != null) { // Multiple files
for (int i = 0; i < data.getClipData().getItemCount(); i++) {
Uri uri = data.getClipData().getItemAt(i).getUri();
Pair<Boolean, File> isValid = isFileValid(uri);
if (isValid.first) {
uriList.add(isValid.second);
}
}
} else { // Single file
Uri uri = data.getData();
Pair<Boolean, File> isValid = isFileValid(uri);
if (isValid.first) {
uriList.add(isValid.second);
}
}
if (uriList.size() > 0) {
for (File file : uriList) {
filesList.add(filesList.size(), file);
filesAdapter.notifyItemInserted(filesList.size());
}
}
}
} catch (Throwable e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private Pair<Boolean, File> isFileValid(Uri uri) throws NullPointerException {
Pair<Boolean, File> defaultResponse = Pair.create(false, null);
Cursor c = getContentResolver().query(uri, null, null, null, null);
if (c != null) {
c.moveToFirst();
String filename = c.getString(c.getColumnIndex(OpenableColumns.DISPLAY_NAME));
if (isSupported(filename)) {
c.close();
return Pair.create(true, new File(StringUtils.endsWithIgnoreCase(filename, ".pdf") ? DOCUMENT : IMAGE));
} else {
Toast.makeText(this, "File format not supported", Toast.LENGTH_SHORT).show();
c.close();
return defaultResponse;
}
}
return defaultResponse;
}
private boolean isSupported(String filename) {
String[] supportedFormats = { ".pdf", ".jpg", ".gif", ".png" };
for (String format : supportedFormats) {
if (StringUtils.endsWithIgnoreCase(filename, format)) {
return true;
}
}
return false;
}
}
Main activity layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="bottom"
android:orientation="vertical"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ImageView
android:id="#+id/attach"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center"
android:layout_marginBottom="19dp"
android:padding="10dp"
android:src="#drawable/ic_attach" />
</LinearLayout>
File:
public class File {
public enum Type {
DOCUMENT,
IMAGE
}
private Type type;
public File(Type type) {
this.type = type;
}
public Type getType() {
return type;
}
}
File Adapter:
public class FilesAdapter extends RecyclerView.Adapter<FilesAdapter.BaseViewHolder> {
private List<File> files;
public FilesAdapter(List<File> files) {
this.files = files;
}
#NonNull
#Override
public FilesAdapter.BaseViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(viewType == 0 ? R.layout.document_item : R.layout.image_item, parent, false);
if (viewType == 0) {
return new DocumentViewHolder(view);
} else {
return new ImageViewHolder(view);
}
}
#Override
public void onBindViewHolder(#NonNull FilesAdapter.BaseViewHolder viewHolder, int position) {
viewHolder.bind(files.get(position));
}
#Override
public int getItemViewType(int position) {
if (files.get(position).getType() == File.Type.DOCUMENT) {
return 0;
} else {
return 1;
}
}
#Override
public int getItemCount() {
return files.size();
}
abstract static class BaseViewHolder extends RecyclerView.ViewHolder {
public BaseViewHolder(#NonNull View itemView) {
super(itemView);
}
abstract void bind(File file);
}
static class ImageViewHolder extends BaseViewHolder {
public ImageViewHolder(#NonNull View itemView) {
super(itemView);
}
#Override
void bind(File file) { }
}
static class DocumentViewHolder extends BaseViewHolder {
public DocumentViewHolder(#NonNull View itemView) {
super(itemView);
}
public void bind(File file) { }
}
}
document item:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="150dp"
android:layout_height="40dp"
android:background="#drawable/ic_rounded"
android:backgroundTint="#888888"
android:layout_margin="5dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="PDF"
android:textColor="#android:color/white"/>
</LinearLayout>
image item:
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="120dp"
android:layout_height="80dp"
android:layout_margin="5dp"
app:cardBackgroundColor="#000000"
app:cardCornerRadius="10dp"
app:cardElevation="0dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="IMAGE"
android:textColor="#android:color/white"/>
</androidx.cardview.widget.CardView>
if I select an image first, and the several pdfs, it works fine:
But if I first select 3 pdfs, and then an image, this happens:
Any idea how to solve this?
I had a similar issue in another project and i solved it by using the Google library FlexboxLayoutManager.
Get the latest FlexboxLayoutManager Library (https://github.com/google/flexbox-layout) and add it into your grandle dependencies (implementation 'com.google.android:flexbox:2.0.1')
In your Activity add the below lines of code: FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(this);
layoutManager.setFlexDirection(FlexDirection.ROW);
layoutManager.setFlexWrap(FlexWrap.NOWRAP);
recyclerView.setLayoutManager(layoutManager);
To make FlexboxLayoutManager work with horizontal scroll add the below code in your adapter (FilesAdapter) in BaseViewHolder class: abstract static class BaseViewHolder extends RecyclerView.ViewHolder {
public BaseViewHolder(#NonNull View itemView) {
super(itemView);
ViewGroup.LayoutParams lp = itemView.getLayoutParams();
if (lp instanceof FlexboxLayoutManager.LayoutParams) {
FlexboxLayoutManager.LayoutParams flexboxLp = (FlexboxLayoutManager.LayoutParams) lp;
flexboxLp.setFlexShrink(0.0f);
flexboxLp.setAlignSelf(AlignItems.FLEX_START); //this will align each itemView on Top or use AlignItems.FLEX_END to align it at Bottom
}
}
abstract void bind(File file);
}
In case it helps anyone else, Kotlin version of MariosP's answer with minor refactors below, but 100% kudos to #MariosP. His answer saved the day for us!
RecyclerView setup (this was from a fragment, called in onViewCreated):
private fun setupRecyclerView() {
val flexBoxLayoutManager = FlexboxLayoutManager(requireContext(), FlexDirection.ROW, FlexWrap.NOWRAP)
with(recycler_view) {
layoutManager = flexBoxLayoutManager
adapter = myAdapter
}
}
Adapter setup:
var items : List<Item>
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.bindItem(items[position])
}
In the ViewHolder:
class MyViewHolder(private val itemView: View): RecyclerView.ViewHolder(itemView) {
fun bindItem(item: Item) {
// Do things with item
updateLayoutParamsToAllowHorizontalScrolling()
}
private fun updateLayoutParamsToAllowHorizontalScrolling() {
(itemView.layoutParams as? FlexboxLayoutManager.LayoutParams)?.let {
it.flexShrink = 0.0f
it.alignSelf = AlignItems.FLEX_START
}
}
}
try this for your RecyclerView:
android:layout_height="wrap_content"
Since the XML file that contains your RecyclerView is not complete here I cannot be sure but if your RecyclerView is inside another parent view that is limiting it, then i guess using wrap_content as the height for RecyclerView plus some tweaks should solve it.
Also, note that you are limiting you RecyclerView to the bottom of "editText" from top side so that may be preventing your RecyclerView from expanding too.
All you have to do, is to set recyclerview's height to the height of the biggest item, in your case the image item.
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="wrap_content"
android:layout_height="80dp" />
The reason Image is getting cropped when you choose pdf files first is because the height of recycleView is 40dp which is the height of pdf item. When you try to add a new item without modifying the existing ones, recycleView height remains the same i.e. 40dp. To enforce a minimum height of 80dp (which is the current height of the image layout), we can use minHeight as follows:
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="80dp"
tools:listitem="#layout/document_item"
/>
You can also modify your pdf item layout to align the pdfs center_vertically with image items as follows:
<?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="match_parent"
android:layout_gravity="center_vertical"
android:layout_margin="5dp">
<TextView
android:layout_width="150dp"
android:layout_height="40dp"
android:layout_gravity="center"
android:gravity="center"
android:background="#drawable/ic_round"
android:backgroundTint="#888888"
android:text="PDF"
android:textColor="#android:color/white"/>
</LinearLayout>
Cheers :)
First, I think your main layout is a bit overcomplicated. You could do the whole thing in a single ConstraintLayout (if you need framed background around specific items, I recommend to use pure View instances layed out using Barriers and Guidelines - see https://medium.com/better-programming/essential-components-of-constraintlayout-7f4026a1eb87)
Another addition and/or improvement would be to not use right/left constraints, rather start/end. This prepares your layout for RTL display too.
Also, I highly recommend to use separate layout files and ViewHolders for distinct items in a RecyclerView.
As others pointed out in comments, your RecyclerView is layed out using match_parent which can in turn crop your view. You may want to set this wrap_content.
In the meanwhile, you may also want to update dependencies to use Android Jetpack and ditch support libraries.
I am developing the Android app in which i want to add 2 imagview at time in layout.The flow is in layout there is one imageview added for taking photo via camera when user take photo from camera when I get the image from camera I will show it in that imageview and that imageview has one cross ImageButton on it's right corner which will get visible when image gets loaded and same thing will happen for another imageview which i want to add when user click photo but i dont know how to add this dynamically. I search for answer but there is only one imageview is added in the layout.Please help me out with this issue.
i want it like this
as show in this image the imageview has cross button on it
as per the solution given by Vijendra i updated my xml and java code but having
error
java.lang.IllegalArgumentException: Cannot add a null child view to a ViewGroup
here is my main.xml:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/bicycle_broken_layout">
<EditText
android:id="#+id/et_moreinfo_broken_bike"
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_marginTop="15dp"
android:hint="#string/more_info"
android:layout_marginStart="25dp"
android:layout_marginEnd="25dp"
android:background="#color/ch_bg"
android:paddingTop="5dp"
android:lines="3"
android:gravity="top|left"
android:inputType="textMultiLine"/>
<RelativeLayout
android:id="#+id/broken_image_photos"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/et_moreinfo_broken_bike"
android:layout_marginTop="20dp">
</RelativeLayout>
<Button
android:id="#+id/btn_submit_report"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/broken_image_photos"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
android:layout_centerHorizontal="true"
android:background="#color/bg_main"
android:text="#string/submit_button"
android:textSize="17sp"
android:textColor="#color/white"
android:padding="15dp"/>
</RelativeLayout>
and here is mainactivity.java
public class Broken_Report_Activity extends AppCompatActivity implements
View.OnClickListener {
private EditText broken_bike_number,broken_bike_location,more_info;
private Button barcode_scanner,location;
private Button submit_report;
private CheckBox seat,pedals,breaks,lock,chain,tier;
private Imageview_add_dynamically photo1,close_photo,framlayout;
RelativeLayout broken_image_layout;
private boolean Isphoto1=false,Isphoto2=false,Isphoto3=false;
private static final int CAMERA_REQUEST = 1888;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_broken_report);
broken_bike_number = (EditText)findViewById(R.id.et_broken_bike_number);
broken_bike_location =
(EditText)findViewById(R.id.et_broken_bike_location);
more_info = (EditText)findViewById(R.id.et_moreinfo_broken_bike);
submit_report = (Button)findViewById(R.id.btn_submit_report);
seat = (CheckBox)findViewById(R.id.ch_seat);
lock = (CheckBox)findViewById(R.id.ch_lock);
chain = (CheckBox)findViewById(R.id.ch_chain);
breaks = (CheckBox)findViewById(R.id.ch_break);
pedals = (CheckBox)findViewById(R.id.ch_pedals);
tier = (CheckBox)findViewById(R.id.ch_tire);
broken_image_layout =
(RelativeLayout)findViewById(R.id.broken_image_photos);
broken_image_layout.addView(photo1);
broken_image_layout.addView(close_photo);
photo1.setOnClickListener(this);
close_photo.setOnClickListener(this);
submit_report.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.broken_img1:
Intent broken_imag_1 = new
Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(broken_imag_1,CAMERA_REQUEST);
break;
case R.id.broken_img1_close:
broken_image_layout.removeView(photo1);
broken_image_layout.removeView(close_photo);
break;
case R.id.btn_submit_report:
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode,resultCode,data);
if(requestCode == CAMERA_REQUEST && resultCode == RESULT_OK){
Bitmap photo = (Bitmap)data.getExtras().get("data");
photo1.getImgPhoto().setImageBitmap(photo);
}
}
In Your xml
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/multipleimages"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
//add your imageview here programatically
</LinearLayout>
</HorizontalScrollView>
In Java code
LinearLayout ll = (LinearLayout) findViewById(R.id.multipleimages);
ImageView imageView1=//your image 1
ImageView imageView2=//your image 2
ll.addView(imageView1);
ll.addView(imageView2);
Im developing a contacts app, and for now Ive been trying to get this drawables from the array get uploaded into the Gridview on the main screen AFTER the save mosaic button is clicked in the mosaic creation screen.
the floating action button (red plus button) on the mosaicListScreen (main screen) leads to the MosaicCreationScreen). the user hypothetically uploads the image and enters the mosaic name then saves using the save mosaic button, as can be seen in the image here
For now, before I focus on uploading image and letting the user create their own unique mosaics (groups), Im testing the Gridview updating with some drawables, which are listed in the array as can be seen in the code below.
The issue thats occuring is as soon as the user clicks the floating action button on the main screen, it updates the gridview with the drawables listed in the array of the MosaicCreation Screen, THEN it goes to the MosaicCreationScreen, and when save mosaic button is clicked on the MosaicCreationScreen, the intent goes to the main screen as its supposed to do, except the gridview will have nothing on it.
so its like its doing the opposite of whats supposed to happen in steps.
here is my code for the two screens:
public class mosaicsListScreen extends AppCompatActivity {
public static mosaicsListScreen theScreen; //this variable is used in the MosaicCreationScreen to point to this screen to find the GridView by id
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
theScreen = this;
setContentView(R.layout.activity_mosaics_list_screen);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.createMosaicButton);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(),MosaicCreationScreen.class);
startActivity(intent);
finish();
}
});
}
}
here is the code for the MosaicCreationScreen (the one that opens after user clicks floating action button from mosaicListScreen (main screen))
public class MosaicCreationScreen extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mosaic_creation_screen);
final GridView mosaicList = (GridView) mosaicsListScreen.theScreen.findViewById(R.id.mosaicList);
mosaicList.setAdapter(new ImageAdapter(this)); //this line of code displays the mosaics on mosaicListScreen
Button saveNewMosaicButton = (Button) findViewById(R.id.saveNewMosaicButton);
saveNewMosaicButton.setOnClickListener(new AdapterView.OnClickListener() {
#Override
public void onClick(View view) {
//mThumbIds.notify();
Intent intent = new Intent(getApplicationContext(), mosaicsListScreen.class);
startActivity(intent);
finish();
//mosaicList.setAdapter(new ImageAdapter(this)); //this displays the mosaics on mosaicListScreen, it logically should go here, however "this" causes an error saying ImageAdapter (android.content.Context) in ImageAdapter cannot be applied to (anonymous android.view.View.OnClickListener)
Toast.makeText(mosaicsListScreen.theScreen, "Mosaic Created!", Toast.LENGTH_SHORT).show();
}
});
/* mosaicList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(mosaicsListScreen.theScreen, "", Toast.LENGTH_SHORT).show();
}
});*/
}
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;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
//this array holds the drawables that would appear on the Gridview
private Integer[] mThumbIds = {
R.drawable.family,
R.drawable.project
};
}
}
Here are the XML for the layouts:
content_mosaics_list_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="codesages.mosaic.mosaicsListScreen"
tools:showIn="#layout/activity_mosaics_list_screen">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/create_a_mosaic_or_pick_from_the_mosaics_created"
android:id="#+id/textView4"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="20sp" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/deleteMosaicButton"
android:src="#android:drawable/ic_menu_delete"
android:clickable="true"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:contentDescription="" />
<GridView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/textView4"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="14dp"
android:id="#+id/mosaicList"
android:layout_above="#+id/textView7"
android:numColumns="auto_fit" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/holdMosaictoDeleteLabel"
android:id="#+id/textView7"
android:layout_marginBottom="16dp"
android:layout_above="#+id/deleteMosaicButton"
android:layout_centerHorizontal="true" />
</RelativeLayout>
activity_mosaics_list_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="codesages.mosaic.mosaicsListScreen">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/createMosaicButton"
android:layout_width="56dp"
android:layout_height="66dp"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_input_add" />
<include layout="#layout/content_mosaics_list_screen" />
</android.support.design.widget.CoordinatorLayout>
activity_mosaic_creation_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="codesages.mosaic.MosaicCreationScreen"
android:focusable="true">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/mosaicNametextField"
android:hint="Mosaic Name"
android:layout_marginTop="81dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save New Mosaic"
android:id="#+id/saveNewMosaicButton"
android:layout_marginTop="48dp"
android:layout_below="#+id/uploadMosaicImageButton"
android:layout_centerHorizontal="true"
android:enabled="true"
android:clickable="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Upload Mosaic Image"
android:id="#+id/uploadMosaicImageButton"
android:layout_marginTop="68dp"
android:layout_below="#+id/mosaicNametextField"
android:layout_centerHorizontal="true"
android:enabled="true"
android:clickable="true" />
</RelativeLayout>
mosaicList.setAdapter(new ImageAdapter(this));
thats what appears to be creating the mosaics. if i comment this out, i wont see anything in the gridview.
however, i believe that should be inside the saveNewMosaicButton onClick, but I am getting an error that says "saying ImageAdapter (android.content.Context) in ImageAdapter cannot be applied to (anonymous android.view.View.OnClickListener)"
HERE is an image example of what the desired result should be. however whats happening right now is as ive stated, as soon as the floating action button is clicked, the mosaics are created, THEN it takes you to the creation screen, in which wehn i click save mosaics, it actually erases the mosaics...a job of the trash icon which is too soon to function for now heh.
appreciate help on this
Currently, you have
public static mosaicsListScreen theScreen;
in your first Activity which you use to fill the ListView in this first Activity. This is a dangerous approach because the Activity instance referenced by this variable may be destroyed, for example if you're doing work in your second Activity (e.g. downloading images) which uses much memory, but also if the user somehow triggers a configuration change.
As you are calling finish() after starting the second Activity, you even tell the system that the first Activity may be destroyed. The only reason you did not get a NPE is that the system destroys the finished Activity not instantly but as soon as it seems a good idea to do so.
All in all, you need a way to safely transmit information from one Activity to the other. In your case, I think you would like to send the Uri of the selected images ( or for now, send the resource id of the selected drawables). Both can be accomplished by using Intent extras.
Basically, there are two options:
use startActivityForResult() and override onActivityResult() to obtain the desired information for the first Activity
simply start the first Activity from the second Activity once you have the result and use getIntent() in the first Activity (e.g. in onCreate()) to check for results
No matter what you do, always access UI elements like the ListView in the Activity to which they belong!
If you choose the second option, your first Activity could look like this:
public class mosaicsListScreen extends AppCompatActivity {
public static final String THUMB_IDS = "someuniquestring";
private GridView mosaicList;
private ArrayList<Integer> mThumbIds;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mosaics_list_screen);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.createMosaicButton);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(),MosaicCreationScreen.class);
startActivity(intent);
finish();
}
});
fillThumbIds();
mosaicList = (GridView) findViewById(R.id.mosaicList);
// Note: Adapter code in this Activity
mosaicList.setAdapter(new ImageAdapter(this));
}
private void fillThumbIds()
{
mThumbIds = new ArrayList();
// somehow get older thumb ids if necessary (from database?)
// and add to ArrayList like this:
mThumbIds.add(R.drawable.family);
mThumbIds.add(R.drawable.project);
// assuming we transmit resource id's: use an int array with the Intent
int[] newThumbIds = getIntent().getIntArrayExtra(THUMB_IDS);
if (newThumbIds != null)
{
// loop through the array to add new thumb ids
for (int i = 0; i < newThumbIds.length; i++) {
mThumbIds.add(newThumbIds[i]);
}
}
}
// Adapter code goes here
// Note: thumbIds no longer as array but as ArrayList!
}
In the second Activity, you put the selected thumb ids as Intent extra as follows:
saveNewMosaicButton.setOnClickListener(new AdapterView.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), mosaicsListScreen.class);
// if 'myNewThumbs' is the int array with the new thumb ids
intent.putExtra(mosaicsListScreen.THUMB_IDS, myNewThumbs);
startActivity(intent);
finish();
}
});
I would appreciate some help, I want to take three photos under the same Intent with startActivityForResults() within a loop, and getting back onActivityResult () which prints those three photos in three imageviews, with MarshMallow, and its specific permissions (I think this is not the issue and it should be solved in my code),
The issue is that the application takes those three pictures, and makes the ArrayList or URIs, but it does not arrive to actually printing those three photos in the three imageviews,
Here is my code, thanks in advance,
-----------------
MainActivity.java
-----------------
public class MainActivity extends AppCompatActivity {
//private int numFotos = 1;
//private Bitmap bitmap;
private ArrayList <Uri> uriFiles;
private ImageView imageView1, imageView2,imageView3;
private Button button_takePics;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_takePics = (Button) findViewById(R.id.Butt_tiraFotos);
imageView1 = (ImageView) findViewById(R.id.image_1);
imageView2 = (ImageView) findViewById(R.id.image_2);
imageView3 = (ImageView) findViewById(R.id.image_3);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
button_takePics.setEnabled(false);
ActivityCompat.requestPermissions(this, new String[]
{ Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 0) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
button_takePics.setEnabled(true);
}
}
}
public void takePictures(View view){
uriFiles = new ArrayList<>();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
for (int i=1; i<4; i++){
uriFiles.add(Uri.fromFile(getOutputMediaFile()));
intent.putParcelableArrayListExtra(MediaStore.EXTRA_OUTPUT,uriFiles);
startActivityForResult(intent, 100);
}
}
private static File getOutputMediaFile() {
File mediaStorageDir=null;
File formattedFile = null;
mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "CameraDemo");
if (!mediaStorageDir.exists()){
if (!mediaStorageDir.mkdirs()){
Log.d("CameraDemo", "failed to create directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
formattedFile= new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
return formattedFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100) {
if (resultCode == RESULT_OK) {
uriFiles = data.getParcelableArrayListExtra(MediaStore.EXTRA_OUTPUT);
// AQUI EMPIEZA EL PROBLEMA ////////
imageView1.setImageURI(uriFiles.get(0));
imageView2.setImageURI(uriFiles.get(1));
imageView3.setImageURI(uriFiles.get(2));
}
}
}
}
-------------------
activity_main.xml
-------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.example.faustocheca.photochooseshare.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="18dp"
android:layout_marginTop="18dp"
android:textSize="18sp"
android:text="Tira, escoge y comparte Fotos" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:hint="Tira 3 Fotos"
android:id="#+id/Butt_tiraFotos"
android:onClick="takePictures"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="48dp"
android:orientation="horizontal"
>
<ImageView
android:id="#+id/image_1"
android:layout_weight="1"
android:layout_width="80dp"
android:layout_height="120dp"
android:layout_margin="1dp"
android:background="#feafea"/>
<ImageView
android:id="#+id/image_2"
android:layout_weight="1"
android:layout_width="80dp"
android:layout_height="120dp"
android:layout_margin="1dp"
android:background="#feafea"/>
<ImageView
android:id="#+id/image_3"
android:layout_weight="1"
android:layout_width="80dp"
android:layout_height="120dp"
android:layout_margin="1dp"
android:background="#feafea"/>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:hint="Comparte"
android:id="#+id/Butt_comparte"
/>
</LinearLayout>
This will not work; a single startActivityForResult will result in a single call to onActivityResult.
There's no contract in the ACTION_IMAGE_CAPTURE documentation or elsewhere in the system that says that you can issue it multiple times and get one result with 3 URIs.
You'll have to loop it so that you fire one intent, wait for the result, fire the second intent, wait for the result, etc.
You may be able to fire the 3 intents in a loop like this, but I'm not sure I'd trust that the responding camera application would actually be invoked 3 times. But even so, you'll receive 3 separate onActivityResult calls, if that works.