I've added buttons into a a cardview and recyclerview. I'm struggling to make the buttons clickable. Every time I click the buttons it's actually registering the recyclerview as being clicked.
Activity containing cardview and recyclerview
package com.khumomashapa.notes.activities;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.khumomashapa.notes.R;
import com.khumomashapa.notes.adapter.RecyclerAdapter;
import com.khumomashapa.notes.arraylists.Messages;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
public class StoreActivity extends AppCompatActivity {
// Widget
RecyclerView recyclerView;
//Firebase
private DatabaseReference mref;
// Variable
private ArrayList<Messages> messagesList;
private RecyclerAdapter recyclerAdapter;
private Context mContext;
Button PurchaseBtn;
Button DownloadBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_store);
recyclerView = findViewById(R.id.products_view);
PurchaseBtn = (Button) findViewById(R.id.PurchaseBtn);
DownloadBtn = (Button) findViewById(R.id.DownloadBtn);
GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
PurchaseBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext()
,recyclerView, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
ImageView imageView = view.findViewById(R.id.ImageView);
Drawable mDrawable = imageView.getDrawable();
Bitmap mBitmap = ((BitmapDrawable)mDrawable).getBitmap();
Intent intent = new Intent(view.getContext(),PreviewActivity.class);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[]bytes = stream.toByteArray();
intent.putExtra("image", bytes);
startActivity(intent);
Messages messages = messagesList.get(position);
Toast.makeText(StoreActivity.this, "You have selected: "+ messages.getTitle(), Toast.LENGTH_SHORT).show();
}
#Override
public void onLongClick(View view, int position) {
}
#Override
public void onButtonClicks(View view, int position) {
}
})
);
// Firebase
mref = FirebaseDatabase.getInstance().getReference();
// Arraylist
messagesList = new ArrayList<Messages>();
// Clear arraylist
ClearAll();
// Get data Method
GetDataFromFirebase();
}
private void GetDataFromFirebase(){
Query query = mref.child("Wallpapers");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
ClearAll();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Messages messages = new Messages();
messages.setImage(snapshot.child("image").getValue().toString());
messages.setTitle(snapshot.child("title").getValue().toString());
messagesList.add(messages);
}
recyclerAdapter = new RecyclerAdapter(getApplicationContext(), messagesList);
recyclerView.setAdapter(recyclerAdapter);
recyclerAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void ClearAll(){
if(messagesList != null){
messagesList.clear();
if (recyclerAdapter !=null){
recyclerAdapter.notifyDataSetChanged();
}
}
messagesList = new ArrayList<Messages>();
}
}
Recycler Adapter
package com.khumomashapa.notes.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.khumomashapa.notes.R;
import com.khumomashapa.notes.activities.StoreActivity;
import com.khumomashapa.notes.arraylists.Messages;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private static final String Tag = "RecyclerView";
private Context mContext;
private ArrayList<Messages> messagesList;
Button PurchaseBtn;
Button DownloadBtn;
View imageView;
public RecyclerAdapter(Context mContext, ArrayList<Messages> messagesArrayList) {
this.mContext = mContext;
this.messagesList = messagesArrayList;
View imageView;
}
#NonNull
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.image, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
// Textview
holder.textView.setText(messagesList.get(position).getTitle());
holder.PurchaseBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
// Imageview: Glide library
Glide.with(mContext)
.load(messagesList.get(position).getImage())
.into(holder.imageView);
}
#Override
public int getItemCount() {
return messagesList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
// Widgets;
ImageView imageView;
TextView textView;
Button PurchaseBtn;
Button DownloadBtn;
View v;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.ImageView);
textView = itemView.findViewById(R.id.Title);
PurchaseBtn = itemView.findViewById(R.id.PurchaseBtn);
DownloadBtn = itemView.findViewById(R.id.DownloadBtn);
View v;
}
}
}
Recycler Touch Listener
package com.khumomashapa.notes.activities
import android.content.Context
import android.view.GestureDetector
import android.view.GestureDetector.SimpleOnGestureListener
import android.view.MotionEvent
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnItemTouchListener
class RecyclerTouchListener(
context: Context?,
recyclerView: RecyclerView,
private val clickListener: ClickListener?
) :
OnItemTouchListener {
private val gestureDetector: GestureDetector
override fun onInterceptTouchEvent(recyclerView: RecyclerView, e: MotionEvent): Boolean {
val child = recyclerView.findChildViewUnder(e.x, e.y)
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, recyclerView.getChildAdapterPosition(child))
}
return false
}
override fun onTouchEvent(recyclerView: RecyclerView, e: MotionEvent) {}
override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {}
interface ClickListener {
fun onClick(view: View?, position: Int)
fun onLongClick(view: View?, position: Int)
fun onButtonClicks(view: View?, position: Int)
}
init {
gestureDetector = GestureDetector(context, object : SimpleOnGestureListener() {
override fun onSingleTapUp(e: MotionEvent): Boolean {
return true
}
override fun onLongPress(e: MotionEvent) {
val child = recyclerView.findChildViewUnder(e.x, e.y)
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildAdapterPosition(child))
}
}
})
}
}
Cardview layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:contentPadding="5dp"
app:cardCornerRadius="10dp"
app:cardUseCompatPadding="true"
app:cardElevation="3dp"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Imagelayout">
<ImageView
android:layout_width="match_parent"
android:layout_height="200dp"
android:scaleType="centerCrop"
android:adjustViewBounds="true"
android:padding="2dp"
android:id="#+id/ImageView"
android:contentDescription="#string/image" />
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/Imagelayout">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/title"
android:textColor="#color/textColor"
android:textSize="20sp"
android:fontFamily="#font/biorhyme_extralight"
android:id="#+id/Title"/>
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/PurchaseBtn"
android:layout_width="350dp"
android:clickable="true"
android:layout_height="40dp"
android:layout_centerInParent="true"
android:onClick="purchase"
android:text="#string/purchase"
android:layout_below="#+id/Title"
android:background="#drawable/btn_rounded"
android:textColor="#color/textColor"
android:textSize="12sp"
app:cornerRadius="20dp"
android:focusable="true" />
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/DownloadBtn"
android:layout_width="350dp"
android:layout_height="40dp"
android:layout_below="#+id/PurchaseBtn"
android:layout_centerInParent="true"
android:layout_centerVertical="true"
android:layout_marginTop="6dp"
android:background="#drawable/btn_rounded"
android:text="#string/download"
android:textColor="#color/textColor"
android:textSize="12sp"
android:visibility="invisible"
app:cornerRadius="20dp" />
</RelativeLayout>
</RelativeLayout>
</androidx.cardview.widget.CardView>
Recyclerview layout
<?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=".activities.StoreActivity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/products_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout >
Another issue I know I'll encounter is the null reference exception.
How do I reference the buttons from the cardview layout when the content view is set to be shown from the other one.
Related
When using a custom adapter in Firebase, I ran into a problem that everything works, but the pictures in the sheet are not displayed. Something incomprehensible is highlighted, but not her. It is necessary that they be in a normal sheet and they can be seen. I think it's because of the context in Picasso. The guide I followed had a wish(mContext) method that I can't use now. Please help, I don't understand what is the problem. I am attaching the image_item.xml code
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/text_view_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:text="Name"
android:textColor="#android:color/black"
android:textSize="20sp" />
<ImageView
android:id="#+id/image_view_upload"
android:layout_width="match_parent"
android:layout_height="200dp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
activity_images
<?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"
tools:context=".ImagesActivity">
<ProgressBar
android:id="#+id/progress_circle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import java.util.List;
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {
private Context mContext;
private List<Upload> mUploads;
public ImageAdapter(Context context, List<Upload> uploads) {
mContext = context;
mUploads = uploads;
}
#Override
public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.image_item, parent, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
Upload uploadCurrent = mUploads.get(position);
holder.textViewName.setText(uploadCurrent.getName());
Picasso.get()
.load(uploadCurrent.getImageUrl())
.placeholder(R.mipmap.ic_launcher)
.fit()
.centerCrop()
.into(holder.imageView);
}
#Override
public int getItemCount() {
return mUploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder {
public TextView textViewName;
public ImageView imageView;
public ImageViewHolder(View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.text_view_name);
imageView = itemView.findViewById(R.id.image_view_upload);
}
}
}
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class ImagesActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private ImageAdapter mAdapter;
private ProgressBar mProgressCircle;
private DatabaseReference mDatabaseRef;
private List<Upload> mUploads;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_images);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mProgressCircle = findViewById(R.id.progress_circle);
mUploads = new ArrayList<>();
mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
mDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Upload upload = postSnapshot.getValue(Upload.class);
mUploads.add(upload);
}
mAdapter = new ImageAdapter(ImagesActivity.this, mUploads);
mAdapter.notifyDataSetChanged();
mRecyclerView.setAdapter(mAdapter);
mProgressCircle.setVisibility(View.INVISIBLE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(ImagesActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
mProgressCircle.setVisibility(View.INVISIBLE);
}
});
}
}
I am trying to implement a search bar for a social media app that displays users with a profile image at the right, the username and the full name aligned vertically next to the image and a follow button at the bottom right that only appears if the user is not following.
I am using a Firebase realtime database to pull data from and the username displays fine but the image and the full name are not displaying and the follow Button is not the right size, as you can see from the image below:
Wrong display
While I need to achieve this:
Correct display
Here is the xml for the user item that will populate the recycler view for the adapter:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/image_profile"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#mipmap/ic_launcher"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#id/image_profile"
android:layout_marginStart="5dp"
android:orientation="vertical"
android:layout_centerVertical="true">
<TextView
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="username"
android:maxLines="1"
android:textStyle="bold"
android:textColor="#color/black"/>
<TextView
android:id="#+id/fullname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Full Name"
android:maxLines="1"/>
</LinearLayout>
<Button
android:id="#+id/btn_follow"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:visibility="gone"/>
</RelativeLayout>
Here the User Adapter:
package com.andrea.uncut.ui.Adapter;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.RecyclerView;
import com.andrea.uncut.R;
import com.andrea.uncut.ui.Model.User;
import com.andrea.uncut.ui.profile.ProfileFragment;
import com.bumptech.glide.Glide;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ViewHolder>{
private Context mContext;
private List<User> mUsers;
private FirebaseUser firebaseUser;
public UserAdapter(Context mContext, List<User> mUsers) {
this.mContext = mContext;
this.mUsers = mUsers;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.user_item, parent, false);
return new UserAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
final User user = mUsers.get(position);
holder.btn_follow.setVisibility(View.VISIBLE);
holder.username.setText(user.getUsername());
holder.fullname.setText(user.getFullname());
Glide.with(mContext).load(user.getImageURL()).into(holder.image_profile);
isFollowing(user.getId(), holder.btn_follow);
if (user.getId().equals(firebaseUser.getUid())){
holder.btn_follow.setVisibility(View.GONE);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences.Editor editor = mContext.getSharedPreferences("PREFS", Context.MODE_PRIVATE).edit();
editor.putString("profileid", user.getId());
editor.apply();
((FragmentActivity)mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ProfileFragment()).commit();
}
});
holder.btn_follow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.btn_follow.getText().toString().equals("follow")){
FirebaseDatabase.getInstance().getReference().child("Follow").child(firebaseUser.getUid())
.child("following").child(user.getId()).setValue(true);
FirebaseDatabase.getInstance().getReference().child("Follow").child(user.getId())
.child("followers").child(firebaseUser.getUid()).setValue(true);
}else{
FirebaseDatabase.getInstance().getReference().child("Follow").child(firebaseUser.getUid())
.child("following").child(user.getId()).removeValue();
FirebaseDatabase.getInstance().getReference().child("Follow").child(user.getId())
.child("followers").child(firebaseUser.getUid()).removeValue();
}
}
});
}
#Override
public int getItemCount() {
return mUsers.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView username;
public TextView fullname;
public CircleImageView image_profile;
public Button btn_follow;
public ViewHolder(#NonNull View itemView){
super(itemView);
username = itemView.findViewById(R.id.username);
fullname = itemView.findViewById(R.id.fullname);
image_profile = itemView.findViewById(R.id.image_profile);
btn_follow = itemView.findViewById(R.id.btn_follow);
}
}
private void isFollowing(String userid, Button button){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference()
.child("Follow").child(firebaseUser.getUid()).child("following");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.child(userid).exists()){
button.setText("following");
}else{
button.setText("follow");
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
Thanks in advance for the help!
This could probably be due to wrap_content value for both the relative layout of user-item and button element.
So trying assigning fixed values to the layout and view.
Also, add font size and padding for the text in the button element to not look distorted or broken.
I am trying to create the image gallery . I am using the recyclerview for the same as there can be large number of images. This is what I am trying to do :
When the user opens up the app android will ask for its permission for images (working)
After selecting either option add it to the image view present in the recyclerview (not working).
If image is saved how to re-render it back to the recyclerview (not working)
Here is what I am trying to do :
This is my Activity file named GalleryActivity.java :
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.traveloholic.R;
import com.traveloholic.models.Gallery;
import java.util.ArrayList;
public class GalleryActivity extends AppCompatActivity {
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
RecyclerView recyclerView = (RecyclerView)findViewById(R.id.imagegallery);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(),2);
recyclerView.setLayoutManager(layoutManager);
Gallery galleryObj = this.getImage();
GalleryAdapter adapter = new GalleryAdapter(GalleryActivity.this, galleryObj);
recyclerView.setAdapter(adapter);
}
private Gallery getImage(){
Gallery galleryObj = new Gallery();
galleryObj.setImageUrl("");
galleryObj.setImageTitle(null);
return galleryObj;
}
public void getImage(ImageView img){
this.imageView = img;
this.selectImage(GalleryActivity.this);
}
private void selectImage(Context context) {
final CharSequence[] options = {"Take Photo", "Choose from Gallery", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose your profile picture");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
Intent takePicture = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);
} else if (options[item].equals("Choose from Gallery")) {
Intent pickPhoto = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, 1);//one can be replaced with any action code
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_CANCELED) {
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK && data != null) {
Bitmap selectedImage = (Bitmap) data.getExtras().get("data");
this.imageView.setImageBitmap(selectedImage);
}
break;
case 1:
if (resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
if (selectedImage != null) {
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
this.imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
cursor.close();
}
}
}
break;
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
}
Here is the layout file activity_galler.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"
tools:context=".activities.GalleryActivity">
<TextView
android:id="#+id/gallery_screen_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/gallery_screen_message"
android:textSize="#dimen/page_identifier_textSize"
android:fontFamily="#font/sanfranciscodisplay_bold"
android:textColor="#color/colorPrimary"
android:layout_marginTop="#dimen/page_identifier_marginTop"
android:textAlignment="center"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"/>
<TextView
android:id="#+id/gallery_screen_submessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:textSize="11sp"
android:layout_below="#id/gallery_screen_message"
android:textColor="#color/black"
android:fontFamily="#font/sanfranciscodisplay_regular"
android:textAlignment="center"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/imagegallery"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/gallery_screen_submessage"
android:layout_marginBottom="85dp"
android:layout_marginTop="#dimen/activity_signup_first_marginTop">
</androidx.recyclerview.widget.RecyclerView>
<Button
android:id="#+id/continue_to_fourth"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/custom_layout_first"
android:fontFamily="#font/sanfranciscodisplay_regular"
android:text="#string/continue_msg"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="18sp"
android:layout_alignParentBottom="true"
android:layout_marginStart="16dp"
android:layout_marginBottom="#dimen/activity_signup_marginBottom"
android:layout_marginEnd="16dp">
</Button>
</RelativeLayout>
Here is the Adapter class GalleryAdapter :
import android.app.Dialog;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import com.traveloholic.R;
import com.traveloholic.models.Gallery;
import java.io.File;
import java.util.ArrayList;
public class GalleryAdapter extends RecyclerView.Adapter<GalleryAdapter.ViewHolder> {
private Gallery galleryObj;
private Context context;
public GalleryAdapter(Context context, Gallery galleryObj) {
this.galleryObj = galleryObj;
this.context = context;
}
#Override
public GalleryAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.image_cell_layout, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final GalleryAdapter.ViewHolder viewHolder, int i) {
viewHolder.img.setImageBitmap(BitmapFactory.decodeFile(galleryObj.getImageUrl()));
}
#Override
public int getItemCount() {
//return galleryList.size();
return 1;
}
public class ViewHolder extends RecyclerView.ViewHolder{
//private TextView title;
private ImageView img;
private ImageButton addRemoveButton;
public ViewHolder(View view) {
super(view);
img = (ImageView) view.findViewById(R.id.img);
addRemoveButton = (ImageButton) itemView.findViewById(R.id.add_remove_icon);
this.addOperationToAddButton();
}
private void addOperationToAddButton(){
addRemoveButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
GalleryActivity galleryActivity = (GalleryActivity)context;
galleryActivity.getImage(img);
}
}
);
}
}
}
Here is my another layout file image_cell_layout.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="#drawable/custom_layout_five"
android:layout_height="150dp"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:id="#+id/image_layout">
<ImageView
android:id="#+id/img"
android:layout_margin="5dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/photo_placeholder" />
<ImageButton
android:id="#+id/add_remove_icon"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:src="#drawable/add_image" />
</RelativeLayout>
Can anyone help me with this how can I solve the three problems mentioned above . Any better aproach to do all this ??
Thanks
I have a RecyclerAdapter in which several images are horizontally placed. How to center each ImageView in item_custom
ListAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import com.example.geometry.R;
import java.util.List;
public class ListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<ItemAdapter> mList;
private Context mContext;
public ListAdapter(List<ItemAdapter> list, Context context){
super();
mList = list;
mContext = context;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int i) {
View v = LayoutInflater.from(mContext).inflate(R.layout.item_custom, parent, false);
final ViewHolder viewHolder = new ViewHolder(v);
viewHolder.mImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Input mode = " + viewHolder.getAdapterPosition(), Toast.LENGTH_SHORT).show();
Builder.mode = viewHolder.getAdapterPosition();
}
});
return viewHolder;
}
#Override
public void onBindViewHolder( RecyclerView.ViewHolder viewHolder, int position) {
ItemAdapter itemAdapter = mList.get(position);
((ViewHolder) viewHolder).mImg.setImageResource(itemAdapter.getImage());
}
#Override
public int getItemCount() {
return mList.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView mTv_name;
public ImageView mImg;
public ViewHolder(View itemView) {
super(itemView);
mImg = (ImageView) itemView.findViewById(R.id.img_item);
}
}
}
ItemAdapter.java
public class ItemAdapter {
private int image;
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
}
MainActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.geometry.GUI.Builder;
import com.example.geometry.GUI.ItemAdapter;
import com.example.geometry.GUI.ListAdapter;
import com.example.geometry.Output.SolveActivity;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecycleView;
private List<ItemAdapter> mList = new ArrayList<>();
private ListAdapter mAdapter;
ListView listView;
RelativeLayout layout;
ImageButton solve_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
addList();
adapter();
}
private void init(){
setContentView(R.layout.activity_main);
layout = new RelativeLayout(this);
mRecycleView = findViewById(R.id.recycler_view);//new RecyclerView(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
mRecycleView.setLayoutParams(params);
}
private void addList(){
ItemAdapter itemAdapter = new ItemAdapter();
itemAdapter.setImage(R.drawable.circle);
mList.add(itemAdapter);
itemAdapter = new ItemAdapter();
itemAdapter.setImage(R.drawable.line);
mList.add(itemAdapter);
itemAdapter = new ItemAdapter();
itemAdapter.setImage(R.drawable.move);
mList.add(itemAdapter);
itemAdapter = new ItemAdapter();
itemAdapter.setImage(R.drawable.angle);
mList.add(itemAdapter);
itemAdapter = new ItemAdapter();
itemAdapter.setImage(R.drawable.regular_triangle);
mList.add(itemAdapter);
itemAdapter = new ItemAdapter();
itemAdapter.setImage(R.drawable.right_triangle);
mList.add(itemAdapter);
itemAdapter = new ItemAdapter();
itemAdapter.setImage(R.drawable.square);
mList.add(itemAdapter);
itemAdapter = new ItemAdapter();
itemAdapter.setImage(R.drawable.trapeze);
mList.add(itemAdapter);
}
private void adapter(){
mAdapter = new ListAdapter(mList, this);
mRecycleView.setAdapter(mAdapter);
mRecycleView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
mAdapter.notifyDataSetChanged();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:id="#+id/solve_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_margin="30dp"
android:background="#drawable/ic_calculator" />
<com.example.geometry.GUI.Builder
android:id="#+id/builder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/recycler_view"
/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
/>
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="Name" />
</RelativeLayout>
item_custom.java
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_margin="2dp"
android:background="#fff"
android:layout_height="wrap_content">
android:layout_gravity="center"
android:scaleType="center">
<ImageView
android:id="#+id/img_item"
android:layout_width="wrap_content"
android:contentDescription="#string/app_name"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:scaleType="center"
android:layout_centerInParent="true"/>
</RelativeLayout>
Change your item_custom according to my code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:background="#fff">
<ImageView
android:id="#+id/img_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_gravity="center"
android:src="#drawable/ic_search"
android:contentDescription="#string/app_name"
android:scaleType="center" />
</RelativeLayout>
Hope it will work definately tested by myself
Happy coding! Thankew!
I'm trying to show a RecyclerView, in a fragment, in my main activity.
I'm not getting any errors, but the fragment remains empty, and I can't find the solution for this problem.
I simply have a fragment that has a recyclerview in it, I configure the recyclerview in HomeFragment.java, then in the MainParkActivity, I have a FrameLayout, which is replaced with the HomeFragment.
MainParkActivity
package com.example.ipark;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;;
public class MainParkActivity extends AppCompatActivity {
private static final String TAG = "MainParkActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate: started.");
Toolbar toolbar = findViewById(R.id.toolbar);
Fragment homeFragment = new HomeFragment();
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("iParc");
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, homeFragment).commit();
}
}
HomeFragment
package com.example.ipark;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
public class HomeFragment extends Fragment {
private static final String TAG = "HomeFragment";
private ArrayList<String> mNames = new ArrayList<>();
private ArrayList<String> mImageUrls = new ArrayList<>();
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
RecyclerView recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
giveInformation();
RecyclerViewAdapter adapter = new RecyclerViewAdapter(getContext(), mNames, mImageUrls);
recyclerView.setAdapter(adapter);
}
private void giveInformation() {
mImageUrls.add("https://loremflickr.com/300/300/bmw");
mNames.add("BMW");
mImageUrls.add("https://loremflickr.com/300/300/bmw");
mNames.add("Audi");
mImageUrls.add("https://loremflickr.com/300/300/bmw");
mNames.add("Hyundai");
mImageUrls.add("https://loremflickr.com/300/300/bmw");
mNames.add("Mercedes");
mImageUrls.add("https://loremflickr.com/300/300/bmw");
mNames.add("BMW");
mImageUrls.add("https://loremflickr.com/300/300/bmw");
mNames.add("Audi");
mImageUrls.add("https://loremflickr.com/300/300/bmw");
mNames.add("Hyundai");
mImageUrls.add("https://loremflickr.com/300/300/bmw");
mNames.add("Mercedes");
}
}
RecyclerViewAdapter
package com.example.ipark;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import de.hdodenhof.circleimageview.CircleImageView;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
private static final String TAG = "RecyclerViewAdapter";
private ArrayList<String> mImageNames;
private ArrayList<String> mImages;
private Context mContext;
public RecyclerViewAdapter(Context mContext, ArrayList<String> mImageNames, ArrayList<String> mImages) {
this.mImageNames = mImageNames;
this.mImages = mImages;
this.mContext = mContext;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_listitem, parent, false);
ViewHolder holder;
holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
Log.d(TAG, "onBindViewHolder: called.");
Glide.with(mContext)
.asBitmap()
.load(mImages.get(position))
.into(holder.image);
holder.imageName.setText(mImageNames.get(position));
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: clicked on: " + mImageNames.get(position));
Toast.makeText(mContext, mImageNames.get(position), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return mImageNames.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
CircleImageView image;
TextView imageName;
RelativeLayout parentLayout;
public ViewHolder(#NonNull View itemView) {
super(itemView);
image = itemView.findViewById(R.id.image);
imageName = itemView.findViewById(R.id.image_name);
parentLayout = itemView.findViewById(R.id.parent_layout);
}
}
}
}
XML for activity_main
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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=".MainParkActivity"
android:clipToPadding="false">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/toolbar">
</FrameLayout>
</android.support.constraint.ConstraintLayout>
XML for fragment_home
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toTopOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
In your fragment_home.xml, your Recyclerview has layout_height and layout_width 0dp. Change it to match_parent. Everything else in your code is correct. I'd have commented it, but I currently do not have commenting privileges! Accept it if you found it helpful!
In your activity_main layout, you have app:layout_constraintBottom_toTopOf="parent"
It should be app:layout_constraintBottom_toBottomOf="parent"
Your layout is currently displaying above the screen in your fragment.
use
adapter.notifyDataSetChanged();
after setting the adapter for RecycleView.