How to implement multiple "Image add" layout? - android

I want to upload multiple images in my db. My question is how to design below screen to upload multiple images.
First: option to add 1st image:
After adding one image, Add option should move to right:
After adding 3 images, the add option should move to left side in 2nd row:
How to design the layout that will move on 2nd row after adding 3 images. Please help to design the above layout. Thank you in advance.

Check out this code.this is not same as u want but it will help u
layout xml file
<?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="com.gennext.android.agrawalcars.UploadImage">
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scroll1"
android:layout_width="match_parent"
android:layout_above="#id/submit"
android:layout_alignParentTop="true"
android:layout_height="wrap_content"
android:scrollbars="none">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<FrameLayout
android:id="#+id/frameLayoutiv"
android:layout_width="match_parent"
android:layout_height="250dp"
android:visibility="gone">
<ImageView
android:id="#+id/imageprofile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#d2000000"
android:scaleType="fitCenter"
android:src="#drawable/cae3"
/>
</FrameLayout>
<GridLayout
android:id="#+id/lnrImages"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_marginBottom="5dp"
android:columnCount="3"
android:rowCount="3">
<android.support.v7.widget.CardView
android:id="#+id/addimage"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_column="0"
android:layout_row="0"
app:cardElevation="5dp"
android:layout_margin="3dp"
android:textAllCaps="false"
app:cardBackgroundColor="#fff"
app:cardCornerRadius="2dp">
<ImageView
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_gravity="center"
android:layout_marginBottom="20dp"
android:src="#drawable/upload_photo"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:fontFamily="#font/noto_serif"
android:layout_marginTop="15dp"
android:text="Add\nCar Photos"
android:textSize="12sp"
/>
</android.support.v7.widget.CardView>
</GridLayout>
</LinearLayout>
</ScrollView>
<Button
android:id="#+id/submit"
android:layout_width="match_parent"
android:layout_height="50dp"
android:textSize="18sp"
android:fontFamily="#font/noto_serif"
android:textStyle="bold"
android:textAllCaps="false"
android:theme="#style/buttonstylescont"
android:layout_alignParentBottom="true"
android:textColor="#color/actionbar_title_color"
android:text="Upload" />
</RelativeLayout>
Activity java file
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.Toast;
import com.vlk.multimager.activities.GalleryActivity;
import com.vlk.multimager.utils.Constants;
import com.vlk.multimager.utils.Image;
import com.vlk.multimager.utils.Params;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
public class UploadImage extends AppCompatActivity {
private String TAG = getClass().getName();
//views
private GridLayout lnrImages;
private CardView btnAddPhots, addinamge;
ImageView imageView1;
FrameLayout frameLayout;
int child;
//imageprocessing
Bitmap bitmap;
int height;
int width;
GridLayout.LayoutParams param = new GridLayout.LayoutParams();
UploadImagesList uploadImagesList;
ArrayList<Image> images;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sellcar_uploadcarphotos);
//uploadimages
uploadImagesList = UploadImagesList.getInstance();
images = uploadImagesList.getImagesList();
// view find
lnrImages = findViewById(R.id.lnrImages);
child=lnrImages.getChildCount();
addinamge = findViewById(R.id.addimage);
imageView1 = findViewById(R.id.imageprofile);
frameLayout = findViewById(R.id.frameLayoutiv);
//get device height
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
height = displayMetrics.heightPixels;
width = displayMetrics.widthPixels;
param.height = width / 3;
param.width = width / 3;
param.rightMargin = 2;
param.topMargin = 2;
param.setGravity(Gravity.CENTER);
addinamge.setLayoutParams(param);
//add btn click
addinamge.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(UploadImage.this, GalleryActivity.class);
Params params = new Params();
params.setCaptureLimit(1);
params.setPickerLimit(1);
params.setToolbarColor(getResources().getColor(R.color.colorAccent));
params.setActionButtonColor(getResources().getColor(R.color.actionbarvtn));
params.setButtonTextColor(getResources().getColor(R.color.textcolor));
intent.putExtra(Constants.KEY_PARAMS, params);
startActivityForResult(intent, Constants.TYPE_MULTI_PICKER);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode != RESULT_OK) {
return;
}
if (intent != null) {
switch (requestCode) {
case Constants.TYPE_MULTI_CAPTURE:
ArrayList<Image> imagesList2 = intent.getParcelableArrayListExtra(Constants.KEY_BUNDLE_LIST);
//setImages(intent);
break;
case Constants.TYPE_MULTI_PICKER:
ArrayList<Image> imagesList = intent.getParcelableArrayListExtra(Constants.KEY_BUNDLE_LIST);
// images=uploadImagesList.getImagesList();
// images.addAll(imagesList);
// uploadImagesList.setImagesList(images);
// Log.d(TAG, "onActivityResult: pickerimages"+imagesList.size());
// Log.d(TAG, "onActivityResult: single imagelist"+uploadImagesList.getImagesList().size());
setImages(imagesList);
// if(uploadImagesList.getImagesList().size()<=8){
// }
//setImages(imagesList);
break;
}
} else {
Toast.makeText(this, "Image not selected", Toast.LENGTH_SHORT).show();
}
}
private void removeallviews() {
for(int i=1;i<lnrImages.getChildCount();i++){
lnrImages.removeViewAt(i);
}
}
private void setImages( ArrayList<Image> imagesList) {
Log.d(TAG, "setImages: single size"+imagesList.size());
Log.d(TAG, "setImages: check child count before delete it"+lnrImages.getChildCount());
if (lnrImages.getChildCount() <= 8) {
if (imagesList.size() != 0) {
Log.d(TAG, "setImages: afterremove child"+lnrImages.getChildCount());
for (int j = 0; j < imagesList.size(); j++) {
bitmap = decodeFile(imagesList.get(j).imagePath);
ImageView imageView = new ImageView(this);
GridLayout.LayoutParams param = new GridLayout.LayoutParams();
param.height = width / 3;
param.width = width / 3;
param.rightMargin = 2;
param.topMargin = 2;
param.setGravity(Gravity.CENTER);
imageView.setLayoutParams(param);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageBitmap(bitmap);
lnrImages.addView(imageView);
child=lnrImages.getChildCount();
Log.d(TAG, "setImages: childcount"+lnrImages.getChildCount());
for (int i = 1; i < lnrImages.getChildCount(); i++) {
final ImageView container = (ImageView) lnrImages.getChildAt(i);
container.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
final Dialog dialog = new Dialog(UploadImage.this, android.R.style.Theme_Light);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().getAttributes().windowAnimations = R.style.Widget_AppCompat_ListPopupWindow;
dialog.getWindow().setBackgroundDrawableResource(R.color.dialogtransprant);
dialog.setContentView(R.layout.dialog_viewsingle_image);
dialog.findViewById(R.id.backarrow).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.findViewById(R.id.deletebtn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Todo : rearrange gridelayout after delete image.
lnrImages.removeViewInLayout(container);
dialog.dismiss();
}
});
dialog.findViewById(R.id.profilebtn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
frameLayout.setVisibility(View.VISIBLE);
float screenWidth=getScreenWidth(UploadImage.this);
float newHeight = screenWidth;
if (bitmap.getWidth() != 0 && bitmap.getHeight() != 0) {
newHeight = (screenWidth * bitmap.getHeight()) / bitmap.getWidth();
}
imageView1.setImageBitmap(((BitmapDrawable) container.getDrawable()).getBitmap());
dialog.dismiss();
}
});
ImageView imageView2 = dialog.findViewById(R.id.imageiv);
imageView2.setImageBitmap(((BitmapDrawable) container.getDrawable()).getBitmap());
dialog.show();
}
});
}
}
} else {
Toast.makeText(this, "please select image", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "only 8 images are uploaded", Toast.LENGTH_SHORT).show();
}
}
/**
* getthis method from this url=https://stackoverflow.com/questions/2521959/how-to-scale-an-image-in-imageview-to-keep-the-aspect-ratio/6143521
* #param activity
* #return
*/
public static float getScreenWidth(Activity activity) {
Display display = activity.getWindowManager().getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics();
display.getMetrics(outMetrics);
float pxWidth = outMetrics.widthPixels;
return pxWidth;
}
private Bitmap decodeFile(String imgPath) {
Bitmap b = null;
int max_size = 1000;
File f = new File(imgPath);
try {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream fis = new FileInputStream(f);
BitmapFactory.decodeStream(fis, null, o);
fis.close();
int scale = 1;
if (o.outHeight > max_size || o.outWidth > max_size) {
scale = (int) Math.pow(2, (int) Math.ceil(Math.log(max_size / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
fis = new FileInputStream(f);
b = BitmapFactory.decodeStream(fis, null, o2);
fis.close();
} catch (Exception e) {
Log.d(TAG, "decodeFile: " + e);
}
return b;
}
}

Layout
camera_lyout.xml
<?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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:id="#+id/camera_shipment_fragment"
tools:context=".view.fragment.CameraShipmentFragment">
<HorizontalScrollView
android:layout_width="0dp"
android:layout_height="390dp"
android:layout_marginStart="1dp"
android:layout_marginEnd="1dp"
android:scrollbars="none"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:id="#+id/gallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
</LinearLayout>
</HorizontalScrollView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16dp"
android:textStyle="bold"
app:layout_editor_absoluteY="0dp"
app:layout_editor_absoluteX="0dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:text="Click below Icon to take Pictures and then click on Save Button to Scan Tag "
tools:ignore="MissingConstraints" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="110dp"
android:layout_height="100dp"
android:layout_marginTop="50dp"
app:srcCompat="#android:drawable/ic_menu_camera"
tools:ignore="MissingConstraints"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="75dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="QR CODE/BARCODE"
android:layout_marginTop="150dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
<ImageView
android:id="#+id/imageView2"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_marginTop="50dp"
android:layout_marginLeft="150dp"
app:srcCompat="#drawable/add_button"
tools:ignore="MissingConstraints"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="75dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/buttonSave"
android:text="Save and Scan"
android:layout_marginTop="330dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
2nd Layout file (item_camera.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp">
<ImageView
android:id="#+id/imageView"
android:layout_marginTop="175dp"
android:layout_width="130dp"
android:layout_height="130dp"
android:background="#drawable/img"
app:srcCompat="#mipmap/ic_launcher" />
<TextView
android:id="#+id/textView"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:textAlignment="center"
android:text="TextView" />
In Camera.java file start camera intent and on activity result write this code
LinearLayout gallery = getView().findViewById(R.id.gallery);
LayoutInflater inflater = LayoutInflater.from(getContext());
View view =inflater.inflate(R.layout.item_camera, gallery,false);
TextView textView =view.findViewById(R.id.textView);
textView.setText("Image" +value);
ImageView imageView =view.findViewById(R.id.imageView);
imageView.setImageBitmap(image);
gallery.addView(view);

Related

Hiding a small line in a RecyclerView ItemTouchHelper

I'm new on Android studio. I made a RecyclerView with a list of data, and I implemented the event on Swiped with an ItemTouchHelper. When I swipe a child from the right to the left I see a small line like in the photo
I would hide this small line. What properties or element of the RecyclerView can be?
Down here the xml file of the activity
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:backgroundTint="?android:attr/colorBackground"
tools:context=".TrippyList">
<LinearLayout
android:id="#+id/linearLayout13"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="#+id/trippyListWelcome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:text="#string/nameLabel"
android:textColor="?attr/colorPrimary"
android:textSize="24sp"
android:textStyle="bold" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginStart="8dp"
android:layout_marginTop="4dp"
android:layout_marginEnd="8dp"
android:text="#string/trippyWelcome2"
android:textColor="?attr/colorPrimary"
android:textSize="24sp"
android:textStyle="bold" />
<View
android:id="#+id/view2"
android:layout_width="300dp"
android:layout_height="2dp"
android:layout_gravity="center"
android:layout_marginTop="16dp"
android:background="#c0c0c0"
android:backgroundTint="?attr/colorPrimary"
android:visibility="visible"
app:layout_constraintWidth_percent="0.7" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout12"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:orientation="horizontal"
app:layout_constraintBottom_toTopOf="#+id/linearLayout9"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<com.google.android.gms.ads.AdView
android:id="#+id/banner_trippylist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="16dp"
android:layout_weight="1"
app:adSize="BANNER"
app:adUnitId="ca-app-pub-3940256099942544/6300978111" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/trippyList_addbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="8dp"
android:clickable="true"
android:src="#drawable/plus"
tools:srcCompat="#android:drawable/ic_menu_add" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout9"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.341"
app:layout_constraintStart_toStartOf="parent">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/navigation_bar_trippy_modify"
android:layout_width="match_parent"
android:layout_height="61dp"
android:elevation="4dp"
android:foregroundTint="?attr/colorAccent"
android:longClickable="false"
app:elevation="4dp"
app:itemIconSize="#dimen/trippy_navbar_size"
app:itemIconTint="?attr/colorAccent"
app:itemTextColor="?attr/colorAccent"
app:menu="#menu/menu" />
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/lista_trippy"
android:layout_width="0dp"
android:layout_height="0dp"
android:cacheColorHint="#00000000"
android:background="#00000000"
android:isScrollContainer="false"
android:keepScreenOn="false"
android:nestedScrollingEnabled="false"
android:overScrollMode="always"
android:requiresFadingEdge="none"
android:scrollIndicators="none"
android:scrollbarAlwaysDrawVerticalTrack="false"
android:scrollbars="vertical"
android:splitMotionEvents="true"
android:verticalScrollbarPosition="defaultPosition"
app:layout_constraintBottom_toTopOf="#+id/linearLayout12"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/linearLayout13"
app:layout_constraintVertical_bias="0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
Down the ItemTouchHelper implementation
ItemTouchHelper touchHelper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(ItemTouchHelper.START, ItemTouchHelper.RIGHT | ItemTouchHelper.LEFT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
ColorDrawable background = null;
Drawable icon = null;
if (dX > 0) {
background = new ColorDrawable(Color.RED);
icon = ContextCompat.getDrawable(getApplicationContext(), R.drawable.bin);
} else {
background = new ColorDrawable(Color.BLUE);
switch (scelta) {
case "1": //delete
icon = ContextCompat.getDrawable(getApplicationContext(), R.drawable.bin);
break;
case "2": // Modifica
icon = ContextCompat.getDrawable(getApplicationContext(), R.drawable.modify);
break;
case "3": // Condividi
icon = ContextCompat.getDrawable(getApplicationContext(), R.drawable.share);
break;
default:
icon = ContextCompat.getDrawable(getApplicationContext(), R.drawable.bin);
break;
}
}
int iconMargin = (viewHolder.itemView.getHeight() - icon.getIntrinsicHeight()) / 2;
int iconTop = viewHolder.itemView.getTop() + (viewHolder.itemView.getHeight() - icon.getIntrinsicHeight()) / 2;
int iconBottom = iconTop + icon.getIntrinsicHeight();
View itemView = viewHolder.itemView;
if (dX > 0) { // Swiping to the right
int iconLeft = itemView.getLeft() + iconMargin;
int iconRight = itemView.getLeft() + iconMargin + icon.getIntrinsicWidth();
icon.setBounds(iconLeft, iconTop, iconRight, iconBottom);
background.setBounds(itemView.getLeft(), itemView.getTop(),
itemView.getLeft() + ((int) dX),
itemView.getBottom());
} else if (dX < 0) { // Swiping to the left
int iconLeft = itemView.getRight() - iconMargin - icon.getIntrinsicWidth();
int iconRight = itemView.getRight() - iconMargin;
icon.setBounds(iconLeft, iconTop, iconRight, iconBottom);
background.setBounds(itemView.getRight() + ((int) dX),
itemView.getTop(), itemView.getRight(), itemView.getBottom());
} else { // view is unSwiped
background.setBounds(0, 0, 0, 0);
}
background.draw(c);
icon.draw(c);
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
AlertDialog.Builder builder = new AlertDialog.Builder(TrippyList.this);
builder.setCancelable(true);
if (direction == 4) {
switch (scelta) {
case "1": //delete
eleminaElemento(builder, viewHolder);
break;
case "2": // Modifica
curtrip = getTrippyDet(viewHolder);
Intent toTrippyMod = new Intent(getApplicationContext(), TrippyModify.class);
toTrippyMod.putExtra("currentTrip", curtrip);
toTrippyMod.putExtra("currentUser", current);
startActivity(toTrippyMod);
myAdapter.notifyItemChanged(viewHolder.getAdapterPosition());
break;
case "3": // Condividi
FragmentManager fm = getSupportFragmentManager();
ShareTrippyFragment stf = new ShareTrippyFragment(trippies.get(viewHolder.getAdapterPosition()), true);
stf.show(fm, "share_trippy_fragment");
myAdapter.notifyItemChanged(viewHolder.getAdapterPosition());
break;
default:
eleminaElemento(builder, viewHolder);
break;
}
} else {
eleminaElemento(builder, viewHolder);
}
}
});
touchHelper.attachToRecyclerView(trippyList);
Down the item layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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="wrap_content"
android:alwaysDrawnWithCache="true"
android:animateLayoutChanges="false">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ImageView
android:id="#+id/trippy_row_icon"
android:layout_width="59dp"
android:layout_height="57dp"
android:layout_marginStart="36dp"
android:layout_marginTop="16dp"
app:srcCompat="#drawable/place_placeholder" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/trippy_row_city"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="100dp"
android:layout_marginTop="16dp"
android:text="#string/trippyNew_city"
android:textColor="?attr/colorPrimary"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="#+id/trippy_row_dates"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="56dp"
android:layout_marginTop="12dp"
android:text="#string/trippyNew_da" />
</LinearLayout>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
and the recyclerview adapter
package com.trippy.trippy.ListAdapters;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.trippy.trippy.Entities.Utente;
import com.trippy.trippy.Entities.Viaggio;
import com.trippy.trippy.R;
import com.trippy.trippy.ActivityModify;
import com.trippy.trippy.TrippyList;
import com.trippy.trippy.TrippyRiepilogo;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
public class TrippyListAdapter extends RecyclerView.Adapter<TrippyListAdapter.MyViewHolder> {
private ArrayList<Viaggio> mDataset;
private Context context;
private Utente curUser;
public static class MyViewHolder extends RecyclerView.ViewHolder {
public View view;
public MyViewHolder(View v) {
super(v);
view = v;
}
}
public TrippyListAdapter(ArrayList<Viaggio> myDataset, Context context) {
mDataset = myDataset;
this.context = context;
}
#NonNull
#Override
public TrippyListAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
// create a new view
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.trippy_list_row, viewGroup, false);
Intent intent = ((Activity) context).getIntent();
curUser = intent.getExtras().getParcelable("currentUser");
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
TextView city = holder.view.findViewById(R.id.trippy_row_city);
TextView date = holder.view.findViewById(R.id.trippy_row_dates);
Viaggio curTrip = mDataset.get(position);
city.setText(curTrip.getLuogo());
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
date.setText(context.getText(R.string.trippy_dal) + " " + format.format(curTrip.getDaData()) + " " + context.getText(R.string.trippy_al) + " " + format.format(curTrip.getaData()));
holder.view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
long now = System.currentTimeMillis();
if(now - TrippyList.canIClick >= 1000) {
TrippyList.canIClick = System.currentTimeMillis();
Intent intent = new Intent(context, TrippyRiepilogo.class);
intent.putExtra("currentTrip", curTrip);
intent.putExtra("currentUser", curUser);
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return mDataset.size();
}
}

First image appearing small in size and on top left corner in a viewpager when rotate the device

Hi in my application i am using the Viewpager with PagerAdapter. it contains n number of images. but when i rotate the device when viewpager is on first image then the image shift to top left corner and appears very small. please have a look in the attached image.
code which i am using
public class CustomViewPager extends ViewPager {
private final long SWITCH_TIME_INTERVAL = 5000;
public CustomViewPager(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public CustomViewPager(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
postDelayed(mSwither, SWITCH_TIME_INTERVAL);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int height = 0;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int h = child.getMeasuredHeight();
if (h > height)
height = h;
}
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
/**
* this Runnable is use for automatically switching the view pager item.
* #author
*/
private Runnable mSwither = new Runnable() {
#Override
public void run() {
if( CustomViewPager.this.getAdapter() != null )
{
int count = CustomViewPager.this.getCurrentItem();
if( count == (CustomViewPager.this.getAdapter().getCount() - 1) )
{
count = 0;
}else
{
count++;
}
//Log.d(this.getClass().getName(), "Curent Page " + count + "");
CustomViewPager.this.setCurrentItem(count, true);
}
CustomViewPager.this.postDelayed(this, SWITCH_TIME_INTERVAL);
}
};
#Override
public boolean onTouchEvent(MotionEvent arg0) {
switch (arg0.getAction()) {
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP :
postDelayed(mSwither, SWITCH_TIME_INTERVAL);
break;
default:
removeCallbacks(mSwither);
break;
}
return super.onTouchEvent(arg0);
} }
//PagerAdapter onInstantiateItem code..
#Override
public Object instantiateItem(ViewGroup container, final int position) {
mImageFetcher.setLoadingImage(R.drawable.placeholder_tabportrait);
inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.test_fragment1, container, false);
description = (TextView) itemView.findViewById(R.id.description);
title = (TextView) itemView.findViewById(R.id.car_title);
published = (TextView) itemView.findViewById(R.id.date_data);
author = (TextView) itemView.findViewById(R.id.author);
jumbo_tron_image = (ImageView) itemView.findViewById(R.id.jumbo_imgae);
TrayItem trayItem = getData(position);
if (null != trayItem) {
if (trayItem.getType() != null) {
if (trayItem.getImages() != null) {
mImageFetcher.loadImage(trayItem.getImages().getWidget(),
jumbo_tron_image);
}
return itemView;
}
//xml code.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="500dp"
android:background="#color/white">
<FrameLayout
android:id="#+id/main_container"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_gravity="center_horizontal|center_vertical"
android:orientation="vertical"
>
<ImageView
android:id="#+id/jumbo_imgae"
android:layout_width="match_parent"
android:scaleType="fitXY"
android:layout_height="300dp"
/>
</FrameLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="#dimen/container_height"
android:layout_below="#+id/main_container">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:orientation="horizontal"
android:id="#+id/linearLayout2">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_alignParentLeft="true"
android:textStyle="bold"
android:layout_weight="0.5"
android:textColor="#color/black"
android:id="#+id/car_title"
android:maxLines="2"
android:ellipsize="end"
android:textSize="20sp"
android:text=" "/>
<ImageView
android:id="#+id/iv_add_test1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:paddingTop="10dp"
android:src="#drawable/add_icon"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/car_title"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/linearLayout2"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:id="#+id/linearLayout3"
android:layout_marginTop="10dp"
android:orientation="horizontal">
<TextView
android:id="#+id/date_data"
android:layout_width="90dp"
android:layout_height="18dp"
android:text=""
android:textSize="13sp"
android:layout_gravity="left"
android:gravity="center"
android:textColor="#color/white"
android:background="#drawable/date_bg"/>
<TextView
android:id="#+id/author"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="15sp"
android:layout_marginLeft="10dp"
android:textColor="#color/black"/>
</LinearLayout>
</LinearLayout>
</RelativeLayout> </RelativeLayout>

How to re-scale Bitmap image size?

Hi guys I am trying to load a image from a url and after loading that i am trying to re scale it such that it fits the whole screen after that the text and the buttons present are available below the image which are wrapped around using scroll view
this is my fragment
public class FirstFragment extends Fragment {
ImageView im;
Bitmap bitmap;
Drawable dr;
Bitmap bitap;
Bitmap newBitmap;
RelativeLayout rel;
View v;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.first_frag, container, false);
rel = (RelativeLayout) v.findViewById(R.id.relativla);
rel.setVisibility(View.INVISIBLE);
new LoadImage().execute("http://opinions.esy.es/bg.jpg");
Button b = (Button) v.findViewById(R.id.navi);
im = (ImageView) v.findViewById(R.id.imageView);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getContext(), Navi.class);
startActivity(i);
}
});
return v;
}
public static FirstFragment newInstance(String text) {
FirstFragment f = new FirstFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream) new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
dr = new BitmapDrawable(getResources(),image);
bitap = ((BitmapDrawable) dr).getBitmap();
float scalingFactor = getBitmapScalingFactor(bitap);
Bitmap newBitmap = Util.ScaleBitmap(bitmap, scalingFactor);
im.setImageBitmap(newBitmap);
}else{
Toast.makeText(getContext(), "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
}
}
}
private float getBitmapScalingFactor(Bitmap bm) {
Toast.makeText(getContext(),"entered here",Toast.LENGTH_LONG).show();
// Get display width from device
int displayWidth = getActivity().getWindowManager().getDefaultDisplay().getWidth();
// Get margin to use it for calculating to max width of the ImageView
RelativeLayout.LayoutParams layoutParams =
(RelativeLayout.LayoutParams)this.im.getLayoutParams();
int leftMargin = layoutParams.leftMargin;
int rightMargin = layoutParams.rightMargin;
// Calculate the max width of the imageView
int imageViewWidth = displayWidth - (leftMargin + rightMargin);
rel.setVisibility(View.VISIBLE);
// Calculate scaling factor and return it
return ( (float) imageViewWidth / (float) bm.getWidth() );
}
}
My Util class
public class Util {
public static Bitmap ScaleBitmap(Bitmap bm, float scalingFactor) {
int scaleHeight = (int) (bm.getHeight() * scalingFactor);
int scaleWidth = (int) (bm.getWidth() * scalingFactor);
return Bitmap.createScaledBitmap(bm, scaleWidth, scaleHeight, true);
}
}
XML File
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/scrollView"
android:fillViewport="true"
>
<RelativeLayout
android:id="#+id/relativla"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<Button
android:layout_width="30dp"
android:layout_height="30dp"
android:background="#drawable/hamburger"
android:id="#+id/navi"
android:padding="10dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:id="#+id/imageView"
android:scaleType="fitCenter"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Diet Plans"
android:padding="10dp"
android:layout_marginTop="10dp"
android:textColor="#android:color/black"
android:textSize="25sp"
android:id="#+id/textView5"
android:layout_below="#+id/imageView"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/descrpitiondietplan"
android:textColor="#000000"
android:gravity="center"
android:layout_gravity="center_vertical"
android:textSize="15sp"
android:padding="10dp"
android:id="#+id/textView6"
android:layout_below="#+id/textView5"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Our Diet Plans"
android:textColor="#android:color/black"
android:padding="10dp"
android:textSize="25sp"
android:id="#+id/textView7"
android:layout_below="#+id/textView6"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/textView7"
android:layout_centerHorizontal="true"
android:padding="10dp">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Basic Diet Plan"
android:textColor="#android:color/white"
android:id="#+id/normmal"
android:background="#color/btn_login"
android:layout_marginBottom="10dp"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</RelativeLayout>
</ScrollView>
It the toast insider the getBitmapScaling factor is called after the relative layout is viewed
Hope you guys can help me solve my issue
try add these
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics dm = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(dm);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(dm.widthPixels, dm.heightPixels);
im.setLayoutParams(params);
below im.setImageBitmap(newBitmap); onPostExecute

how to make Footer buttons appears while dragging screen down in android like in facebook app

I wanna make footer buttons in android one way is to simply make buttons and align them to bottom but I want the footer like in Facebook android app whenever we drag screen down three buttons appears for status , photo , checkin.
How to do this ??
To get a list like the following image, create a layout.xml as follows after the sample image
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white" >
<RelativeLayout
android:id="#+id/headerLayout"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#drawable/header" >
<LinearLayout
android:id="#+id/BtnSlide"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:background="#drawable/button_bg_drawable" >
<ImageView
android:id="#+id/imageView0"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_gravity="center_vertical|left"
android:background="#drawable/button_bg_drawable"
android:paddingBottom="10dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:paddingTop="10dp"
android:src="#drawable/back_btn_small" />
</LinearLayout>
<EditText
android:id="#+id/headerText"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:layout_toRightOf="#id/BtnSlide"
android:background="#android:drawable/editbox_background_normal"
android:editable="false"
android:textColor="#color/black"
android:textSize="18sp"
android:textStyle="normal" />
<AutoCompleteTextView
android:id="#+id/filterNewProject"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:layout_toRightOf="#id/BtnSlide"
android:background="#drawable/bg_input_blue"
android:completionThreshold="1"
android:hint="Search for a locality, developer or project"
android:textColor="#color/black"
android:textSize="14sp"
android:visibility="gone" />
<Button
android:id="#+id/clearAutoCompleteList"
android:layout_width="18dp"
android:layout_height="18dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:background="#drawable/custom_button_clear"
android:paddingLeft="20dp"
android:visibility="gone" />
<Button
android:id="#+id/searchButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="15dp"
android:background="#drawable/seaerch_glass" />
<View
android:id="#+id/sep_header"
android:layout_width="fill_parent"
android:layout_height="2dp"
android:layout_below="#id/tabBar"
android:background="#d5d5d5"
android:visibility="visible" />
</RelativeLayout>
<include
android:id="#+id/footerLayout"
layout="#layout/post_requirement_footer"
android:visibility="gone" />
<ListView
android:id="#+id/projectsList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/footerLayout"
android:layout_below="#id/headerLayout"
android:divider="#color/white"
android:dividerHeight="1.5dp" >
</ListView>
<RelativeLayout
android:id="#+id/zeroResultsLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/footerLayout"
android:layout_below="#id/headerLayout"
android:visibility="gone" >
<ImageView
android:id="#+id/emptyIllustration"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="#drawable/no_results_illustration" />
</RelativeLayout>
<com.housing.utils.QuickReturnRelativeLayoutFooter
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:background="#color/transparent" >
<RelativeLayout
android:id="#+id/bottomListViewContainer"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:background="#drawable/footer_bg" >
<ImageButton
android:id="#+id/filterButtonFooter"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:background="#drawable/button_bg_drawable"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:src="#drawable/filter_icon" />
<ImageButton
android:id="#+id/subscribeButtonFooter"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:background="#drawable/button_bg_drawable"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:src="#drawable/subscribe_iphone"
android:visibility="visible" />
<TextView
android:id="#+id/resultsText"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:ellipsize="end"
android:paddingTop="10dp"
android:scrollHorizontally="false"
android:singleLine="false"
android:text=""
android:textColor="#color/black"
android:textSize="15dp"
android:visibility="visible" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#id/resultsText"
android:paddingRight="5dp"
android:paddingTop="15dp"
android:src="#drawable/filter_normal"
android:visibility="gone" />
</RelativeLayout>
</com.housing.utils.QuickReturnRelativeLayoutFooter>
</RelativeLayout>
Here is the Class com.housing.utils.QuickReturnRelativeLayoutFooter
PS : Replace com.housing.utils with your package name
package com.housing.utils;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.RelativeLayout;
public class QuickReturnRelativeLayoutFooter extends RelativeLayout implements
OnScrollListener {
private class ChildDescriptor {
public int index;
public int total;
public int drawable;
public ChildDescriptor(int index) {
this.index = index;
}
public int getApproximateScrollPosition() {
return index * total + (total - drawable);
}
}
public int MAX_HEIGHT_DP =60;
public int MIN_HEIGHT_DP = 0;
public static final int SCROLL_DIRECTION_INVALID = 0;
public static final int SCROLL_DIRECTION_UP = 1;
public static final int SCROLL_DIRECTION_DOWN = 2;
private int direction = SCROLL_DIRECTION_INVALID;
private ChildDescriptor lastchild;
private OnScrollListener onscrolllistener;
private int maxheight;
private int minheight;
public QuickReturnRelativeLayoutFooter(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
calculateMinMax();
}
public QuickReturnRelativeLayoutFooter(Context context, AttributeSet attrs) {
super(context, attrs);
calculateMinMax();
}
public QuickReturnRelativeLayoutFooter(Context context) {
super(context);
calculateMinMax();
}
private void calculateMinMax() {
DisplayMetrics metrics = getResources().getDisplayMetrics();
maxheight = (int) (metrics.density * (float) MAX_HEIGHT_DP);
minheight = (int) (metrics.density * (float) MIN_HEIGHT_DP);
}
private void adjustHeight(int howmuch, int max, int min) {
if ((howmuch < 0) && (direction != SCROLL_DIRECTION_UP)) {
direction = SCROLL_DIRECTION_UP;
return;
} else if ((howmuch > 20) && (direction != SCROLL_DIRECTION_DOWN)) {
direction = SCROLL_DIRECTION_DOWN;
return;
}
int current = getHeight();
current += howmuch;
if (current < min) {
current = min;
} else if (current > max) {
current = max;
}
RelativeLayout.LayoutParams f = (RelativeLayout.LayoutParams) getLayoutParams();
if (f.height != current) {
f.height = current;
setLayoutParams(f);
}
if (direction == SCROLL_DIRECTION_UP
&& Math.abs(f.topMargin) <= current) {
// if (f.topMargin != howmuch) {
//
// f.topMargin = howmuch + f.topMargin;
//
// if (f.topMargin > 0) {
// f.topMargin = -f.topMargin - 10;
// }
//
// }
// mBottomListViewContainer.setVisibility(View.GONE);
f.bottomMargin = -100;
setLayoutParams(f);
} else if (direction == SCROLL_DIRECTION_DOWN) {
if (f.bottomMargin != 0) {
f.bottomMargin = 0;
setLayoutParams(f);
}
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
ChildDescriptor currentchild = getFirstChildItemDescriptor(view,
firstVisibleItem);
try {
adjustHeight(lastchild.getApproximateScrollPosition()
- currentchild.getApproximateScrollPosition(), maxheight,
minheight);
lastchild = currentchild;
} catch (NullPointerException e) {
lastchild = currentchild;
} catch (Exception e) {
}
if (onscrolllistener != null) {
onscrolllistener.onScroll(view, firstVisibleItem, visibleItemCount,
totalItemCount);
}
}
private ChildDescriptor getFirstChildItemDescriptor(AbsListView view,
int index) {
ChildDescriptor h = new ChildDescriptor(index);
try {
Rect r = new Rect();
View child = view.getChildAt(0);
child.getDrawingRect(r);
h.total = r.height();
view.getChildVisibleRect(child, r, null);
h.drawable = r.height();
return h;
} catch (Exception e) {
}
return null;
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (onscrolllistener != null) {
onscrolllistener.onScrollStateChanged(view, scrollState);
}
}
public void attach(AbsListView view) {
view.setOnScrollListener(this);
}
public void setOnScrollListener(OnScrollListener l) {
onscrolllistener = l;
}
}
I Have made it as a widget and Now finally to add this to your List View use
frame = (QuickReturnRelativeLayoutFooter) newProjectsView
.findViewById(R.id.frame);
frame.attach(projectsList);
where projectList is your List View
example
ListView projectList =(ListView)findViewById(R.id.projectList);
and Voila Cheers Completed Smooth as Heaven .......

Android custom TextView not intercepting OnClickListener of parent

I've made a custom TextView that draws lines for every line of text.
This custom TextView is placed in a LinearLayout along with other standard TextViews and ImageViews.
Whenever I click the normal TextViews, ImageViews or outside the custom TextView, the click is intercepted.
But, if I click on the custom TextView, the click is not intercepted.
Please help!!!
Images:
Normal state(minimized)
Maximized state
Click not detected here
Code:
NoteTextView.java
package harsha.notes.view;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.TextView;
public class NoteTextView extends TextView {
boolean isMaximized = false;
public NoteTextView(Context canvas, AttributeSet attributeSet) {
super(canvas, attributeSet);
}
#Override
protected void onDraw(Canvas canvas) {
int width = getWidth();//var2.getDefaultDisplay().getWidth();
int height = getHeight();//var2.getDefaultDisplay().getHeight();
int paddingLeft = getPaddingLeft();
int paddingTop = getPaddingTop();
int paddingBottom = getPaddingBottom();
int scrollY = getScrollY();
int scrollX = getScrollX();
int lineHeight = getLineHeight();
int grossWidth = width + scrollX;
int grossHeight = height + scrollY;
int netViewHeight = lineHeight + (grossHeight - paddingTop - paddingBottom);
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
//paint.setColor(1722066084);
paint.setColor(1711276032);
float fontAdjustment = 15.826172F - (paint.getFontMetrics().bottom - paint.getFontMetrics().top);
float baseline = (float)(scrollY + lineHeight - scrollY % lineHeight) - fontAdjustment;
float linePadding;
if(width != 800 && height != 480) {
linePadding = 2;
} else {
linePadding = 4;
}
while(baseline < (float)netViewHeight) {
canvas.drawLine((float)paddingLeft, baseline + (float)paddingTop + linePadding, (float)grossWidth, baseline + (float)paddingTop + linePadding, paint);
baseline += (float)lineHeight;
}
super.onDraw(canvas);
}
public boolean isMaximized(){
return isMaximized;
}
public void setMaximized(boolean maximized){
isMaximized = maximized;
if(!isMaximized){
setLines(1);
}else{
setSingleLine(false);
}
}
}
NoteListAdapter.java
package harsha.notes.Items;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import harsha.notes.DB.NotesProvider;
import harsha.notes.NoteEditActivity;
import harsha.notes.R;
import harsha.notes.view.NoteTextView;
import harsha.notes.view.ViewUtils;
import java.util.ArrayList;
public class NoteListAdapter extends ArrayAdapter<Note> {
ArrayList<Note> mNotes;
final Context mContext;
public NoteListAdapter(Context context, ArrayList<Note> notes) {
super(context, R.layout.note_item, notes);
mContext = context;
mNotes = new ArrayList<Note>();
mNotes = notes;
}
public class NoteViewHolder {
public LinearLayout preview_layout;
public TextView position;
public TextView date;
public TextView time;
//public CheckBox check;
public ImageView edit;
public ImageView delete;
public NoteTextView content;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
NoteViewHolder noteViewHolder = null;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.note_item, null);
noteViewHolder = new NoteViewHolder();
noteViewHolder.preview_layout = (LinearLayout) convertView.findViewById(R.id.preview);
noteViewHolder.position = (TextView) convertView.findViewById(R.id.position);
noteViewHolder.date = (TextView) convertView.findViewById(R.id.date);
noteViewHolder.time = (TextView) convertView.findViewById(R.id.time);
noteViewHolder.edit = (ImageView) convertView.findViewById(R.id.menu_edit);
noteViewHolder.delete = (ImageView) convertView.findViewById(R.id.menu_delete);
//noteViewHolder.check = (CheckBox) convertView.findViewById(R.id.check);
noteViewHolder.content = (NoteTextView) convertView.findViewById(R.id.preview_text);
}else{
noteViewHolder = (NoteViewHolder) convertView.getTag();
}
Note note = mNotes.get(position);
noteViewHolder.content.setMaximized(note.getChecked());
noteViewHolder.content.setNextFocusUpId(R.id.preview);
noteViewHolder.preview_layout.setBackgroundResource(ViewUtils.getBackground(note.getColor(), noteViewHolder.content.isMaximized()));
noteViewHolder.content.setText(note.getText());
//noteViewHolder.check.setVisibility(View.GONE);
noteViewHolder.date.setText(note.getDate());
noteViewHolder.time.setText(note.getTime());
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view){
LinearLayout preview_layout = (LinearLayout) view.findViewById(R.id.preview);
NoteTextView content = (NoteTextView) view.findViewById(R.id.preview_text);
Note note = (Note) preview_layout.getTag();
content.setMaximized(!note.getChecked());
preview_layout.setBackgroundResource(ViewUtils.getBackground(note.getColor(), !note.getChecked()));
note.setChecked(!note.getChecked());
}
});
noteViewHolder.edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LinearLayout preview_layout = (LinearLayout) view.getRootView().findViewById(R.id.preview);
Note note = (Note) preview_layout.getTag();
Intent intent = new Intent(mContext, NoteEditActivity.class);
intent.setData(Uri.withAppendedPath(NotesProvider.CONTENT_URI, Uri.encode(String.valueOf(note.getNoteID()))));
mContext.startActivity(intent);
}
});
noteViewHolder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LinearLayout preview_layout = (LinearLayout) view.findViewById(R.id.preview);
Note note = (Note) preview_layout.getTag();
}
});
noteViewHolder.position.setText(String.valueOf(position+1));
noteViewHolder.preview_layout.setTag(note);
convertView.setTag(noteViewHolder);
return convertView;
}
}
note_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="#id/preview_parent" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" android:background="#ff4A4A4A" android:padding="5dip" android:measureWithLargestChild="false"
android:clickable="true" android:focusable="true">
<LinearLayout android:id="#id/preview" android:focusable="true" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" android:background="#drawable/note_yellow_min"
android:focusableInTouchMode="true">
<LinearLayout android:layout_width="fill_parent" android:layout_height="40dip" android:layout_marginRight="0dp" android:layout_marginBottom="1dip" android:gravity="center_vertical" android:focusable="false"
android:layout_marginTop="1dip">
<ImageView android:id="#id/menu_edit" android:layout_width="37dip" android:layout_height="37dip" android:src="#drawable/menu_edit" android:contentDescription="#string/color_yellow"
android:clickable="true" android:layout_marginLeft="2dip"/>
<TextView android:id="#id/position" android:textSize="15.0dip" android:typeface="sans" android:textStyle="bold" android:textColor="#ff000000" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="MMM" android:layout_gravity="center" android:layout_marginLeft="5dip" android:gravity="right"
android:focusable="false"/>
<TextView android:id="#id/date" android:textSize="17.0dip" android:typeface="sans" android:textStyle="bold" android:textColor="#ff000000" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="16 AUG 2001" android:layout_weight="1" android:layout_gravity="center" android:layout_marginLeft="8dip"
android:textIsSelectable="false" android:focusable="false"/>
<TextView android:id="#id/time" android:textSize="17.0dip" android:typeface="sans" android:textStyle="bold" android:textColor="#ff000000" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="20:11" android:layout_gravity="center" android:layout_marginLeft="8dip" android:layout_marginRight="8dip"
android:textIsSelectable="false" android:focusable="false"/>
<ImageView android:id="#id/menu_delete" android:layout_width="37dip" android:layout_height="37dip" android:src="#drawable/menu_delete" android:contentDescription="#string/color_yellow"
android:clickable="true" android:layout_marginLeft="2dip" android:layout_marginRight="3dip"
android:visibility="visible"/>
<ImageView android:id="#id/check" android:layout_width="37dip" android:layout_height="37dip" android:src="#drawable/menu_check" android:contentDescription="#string/color_yellow"
android:clickable="true" android:layout_marginLeft="0dp" android:layout_marginRight="3dip"
android:visibility="gone"/>
</LinearLayout>
<View android:layout_width="fill_parent" android:layout_height="1dip" android:background="#77000000" android:focusable="false"/>
<harsha.notes.view.NoteTextView android:scrollbarStyle="outsideOverlay" android:autoLink="all" android:capitalize="sentences" android:lineSpacingExtra="4.0dip" android:text="123" android:textColor="#ff000000" android:minLines="1" android:id="#id/preview_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="22dp" android:layout_marginLeft="20dp" android:layout_marginRight="25dip" android:layout_marginTop="3dip" android:layout_marginBottom="28dip" android:clickable="true"
android:typeface="sans" android:visibility="visible" android:focusable="false"
android:background="#android:color/transparent" android:linksClickable="true"
android:focusableInTouchMode="false" android:longClickable="true"
android:enabled="true"/>
</LinearLayout>
</LinearLayout>
try setting onFocusChanged listener to edittext.
Did you mean that, when you click on custom TextView, your convertView's OnClickListener didn't called onClick()?
If yes, you could try disable the custom TextView.
<harsha.notes.view.NoteTextView android:scrollbarStyle="outsideOverlay" android:autoLink="all" android:capitalize="sentences" android:lineSpacingExtra="4.0dip" android:text="123" android:textColor="#ff000000" android:minLines="1" android:id="#id/preview_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="22dp" android:layout_marginLeft="20dp" android:layout_marginRight="25dip" android:layout_marginTop="3dip" android:layout_marginBottom="28dip" android:clickable="true"
android:typeface="sans" android:visibility="visible" android:focusable="false"
android:background="#android:color/transparent" android:linksClickable="true"
android:focusableInTouchMode="false" android:longClickable="true"
android:enabled="false"/>

Categories

Resources