Hiding a small line in a RecyclerView ItemTouchHelper - android

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();
}
}

Related

How to implement multiple "Image add" layout?

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);

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 scroll up/down of bottom bar on scrolling of RecyclerView

With Google’s recent release of the Design Support Library several cool new views have been introduced. Using some of the new components (e.g. CoordinatorLayout ) might (!) enable you to achieve the scrolling behavior.
I was tryed with some built in scrolling behavior but nothing is working for me,
I have a bottombar(LinearLayout) in my layout in place of FloatingActionButton
Here what I want.
OnLaunch of this screen bottom bar should appear.
On scrollup of recyclerview bottom bar should scrolldown.
On scrolldown of recyclerview bottom bar should scrollup
Is there any builtin mechanism to achieve this ? or We need write java code?
Here is my code:
main_activty.xml
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<include layout="#layout/toolbar_srp" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="5dp"
app:tabGravity="fill"
app:tabIndicatorColor="#android:color/white"
app:tabMode="fixed" />
</android.support.design.widget.AppBarLayout>
<!-- All Scrollable Views -->
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<!-- Bottom bar-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="#a0000000"
android:orientation="horizontal"
android:paddingBottom="#dimen/padding_small"
android:paddingTop="#dimen/padding_small">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.33"
android:gravity="center"
android:paddingBottom="#dimen/padding_small"
android:paddingTop="#dimen/padding_small"
android:text="AC"
android:textColor="#color/white" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.33"
android:gravity="center"
android:paddingBottom="#dimen/padding_small"
android:paddingTop="#dimen/padding_small"
android:text="Sleeper"
android:textColor="#color/white" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.33"
android:gravity="center"
android:paddingBottom="#dimen/padding_small"
android:paddingTop="#dimen/padding_small"
android:text="Premium"
android:textColor="#color/white" />
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
fragment.xml (here I was putted my recyclerview code)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingBottom="#dimen/padding_small"
android:paddingTop="#dimen/padding_small"
android:weightSum="1">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.33"
android:background="#drawable/bg_srp_sorter"
android:clickable="true"
android:gravity="center"
android:paddingBottom="#dimen/padding_small"
android:paddingTop="#dimen/padding_small"
android:text="Departure" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.33"
android:background="#drawable/bg_srp_sorter"
android:gravity="center"
android:paddingBottom="#dimen/padding_small"
android:paddingTop="#dimen/padding_small"
android:text="Duration" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.33"
android:gravity="center"
android:paddingBottom="#dimen/padding_small"
android:paddingTop="#dimen/padding_small"
android:text="Price" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/lite_gray"></View>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:weightSum="1">
<android.support.v7.widget.RecyclerView
android:id="#+id/bus_list_recycler_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
</LinearLayout>
toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
android:minHeight="?attr/actionBarSize">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="1">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.10">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/abc_ic_ab_back_mtrl_am_alpha" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.78"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="1">
<TextView
android:id="#+id/toolbar_title_source"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.47"
android:ellipsize="end"
android:singleLine="true"
android:text="Thiruvananthapuram "
android:textColor="#color/white"
android:textSize="#dimen/label_text_size_large" />
<TextView
android:id="#+id/toolbar_title_arrow"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.08"
android:text="#string/char_right"
android:textColor="#color/white"
android:textSize="#dimen/label_text_size_large"
android:textStyle="bold" />
<TextView
android:id="#+id/toolbar_title_destination"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.47"
android:ellipsize="end"
android:singleLine="true"
android:text=" Cochin"
android:textColor="#color/white"
android:textSize="#dimen/label_text_size_large" />
</LinearLayout>
<TextView
android:id="#+id/toolbar_sub_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2 Seat(s)"
android:textColor="#color/lite_gray"
android:textSize="#dimen/label_text_size_normal" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.13">
<ImageView
android:layout_width="30dp"
android:layout_height="30dp"
android:scaleType="fitCenter"
android:src="#drawable/filter" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.Toolbar>
This how I did it:
mRecylerView.addOnScrollListener(new HideShowScrollListener() {
#Override
public void onHide() {
//fab.animate().setInterpolator(new AccelerateDecelerateInterpolator()).scaleX(0).scaleY(0);
// do your hiding animation here
}
#Override
public void onShow() {
// fab.animate().setInterpolator(new AccelerateDecelerateInterpolator()).scaleX(1).scaleY(1);
// do your showing animation here
}
});
You will be needing HideShowScrollListener.class
/**
* This class is a ScrollListener for RecyclerView that allows to show/hide
* views when list is scrolled.
* */
public abstract class HideShowScrollListener extends RecyclerView.OnScrollListener {
private static final int HIDE_THRESHOLD = 20;
private int scrolledDistance = 0;
private boolean controlsVisible = true;
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (scrolledDistance > HIDE_THRESHOLD && controlsVisible) {
onHide();
controlsVisible = false;
scrolledDistance = 0;
} else if (scrolledDistance < -HIDE_THRESHOLD && !controlsVisible) {
onShow();
controlsVisible = true;
scrolledDistance = 0;
}
if((controlsVisible && dy>0) || (!controlsVisible && dy<0)) {
scrolledDistance += dy;
}
}
public abstract void onHide();
public abstract void onShow();
}
since you are using CoordinatorLayout you could create a custom Behaviour that can achieve what you requested follow example below:
create a class that extends CoordinatorLayout.Behavior<View> follow example below:
public class QuickReturnFloaterBehavior extends CoordinatorLayout.Behavior<View> {
private int distance;
public QuickReturnFloaterBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout, View child, View directTargetChild, View target, int nestedScrollAxes) {
return (nestedScrollAxes & ViewCompat.SCROLL_AXIS_VERTICAL) != 0;
}
#Override public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, View child, View target, int dx, int dy, int[] consumed) {
if (dy > 0 && distance < 0 || dy < 0 && distance > 0) {
child.animate().cancel();
distance = 0;
}
distance += dy;
final int height = child.getHeight() > 0 ? (child.getHeight()) : 600/*update this accordingly*/;
if (distance > height && child.isShown()) {
hide(child);
} else if (distance < 0 && !child.isShown()) {
show(child);
}
}
private void hide(View view) {
view.setVisibility(View.GONE);// use animate.translateY(height); instead
}
private void show(View view) {
view.setVisibility(View.VISIBLE);// use animate.translateY(-height); instead
}
}
now to apply this behaviour add this to your layout
app:layout_behavior="com.example.QuickReturnFloaterBehavior"
Visibility and Hide with Animation in Your Fragment:
recyclerView.addOnScrollListener(new HideShowScrollListener() {
final Fragment parentFragment = getParentFragment();
#Override
public void onHide() {
bottomLayout.animate().setDuration(200).translationYBy(-bottomLayout.getHeight()).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
bottomLayout.setVisibility(View.GONE);
}
});
}
#Override
public void onShow() {
bottomLayout.animate().setDuration(200).translationY(0).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
bottomLayout.setVisibility(View.VISIBLE);
}
});
}
#Override
public void onScrolled() {
// To load more data
}
});
HideShowScrollListener.java
public abstract class HideShowScrollListener extends RecyclerView.OnScrollListener {
private static final int HIDE_THRESHOLD = 20;
private int scrolledDistance = 0;
private boolean controlsVisible = true;
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
onScrolled();
if (scrolledDistance > HIDE_THRESHOLD && controlsVisible) {
onHide();
controlsVisible = false;
scrolledDistance = 0;
} else if (scrolledDistance < -HIDE_THRESHOLD && !controlsVisible) {
onShow();
controlsVisible = true;
scrolledDistance = 0;
}
if((controlsVisible && dy>0) || (!controlsVisible && dy<0)) {
scrolledDistance += dy;
}
}
public abstract void onHide();
public abstract void onShow();
public abstract void onScrolled();
}
package com.keshav.hideactionbarandfooterexample;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import java.util.ArrayList;
import java.util.List;
import adapters.RecyclerAdapter;
import listners.HidingScrollListener;
public class MainActivity extends AppCompatActivity {
private Toolbar mToolbar;
private Toolbar toolbar_bottom;
private ImageButton mFabButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.AppThemeRed);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.e("keshav", "MainActivity called");
initToolbar();
mFabButton = (ImageButton) findViewById(R.id.fabButton);
initRecyclerView();
}
private void initToolbar() {
mToolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar_bottom = (Toolbar) findViewById(R.id.toolbar_bottom);
setSupportActionBar(mToolbar);
setSupportActionBar(toolbar_bottom);
setTitle(getString(R.string.app_name));
mToolbar.setTitleTextColor(getResources().getColor(android.R.color.white));
toolbar_bottom.setTitleTextColor(getResources().getColor(android.R.color.white));
toolbar_bottom.setVisibility(View.GONE);
}
private void initRecyclerView() {
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
RecyclerAdapter recyclerAdapter = new RecyclerAdapter(createItemList());
recyclerView.setAdapter(recyclerAdapter);
recyclerView.addOnScrollListener(new HidingScrollListener() {
#Override
public void onHide() {
hideViews();
}
#Override
public void onShow() {
showViews();
}
});
}
private void hideViews() {
// TODO (-mToolbar) plus means 2 view above ho jaye or not visible to user
mToolbar.animate().translationY(-mToolbar.getHeight()).setInterpolator(new AccelerateInterpolator(2));
// TODO uncomment this Hide Footer in android when Scrolling
// TODO (+mToolbar) plus means 2 view forward ho jaye or not visible to user
toolbar_bottom.animate().translationY(+toolbar_bottom.getHeight()).setInterpolator(new AccelerateInterpolator(2));
// TODO keshav Hide Also Floatng Button In Android
FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mFabButton.getLayoutParams();
int fabBottomMargin = lp.bottomMargin;
mFabButton.animate().translationY(mFabButton.getHeight() + fabBottomMargin).setInterpolator(new AccelerateInterpolator(2)).start();
// TODO keshav Hide Also Floatng Button In Android
}
private void showViews() {
mToolbar.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2));
// TODO uncomment this Hide Footer in android when Scrolling
toolbar_bottom.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2));
mFabButton.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2)).start();
}
private List<String> createItemList() {
List<String> itemList = new ArrayList<>();
for (int i = 0; i < 20; i++) {
itemList.add("Item " + i);
}
return itemList;
}
}
=============================================
RecyclerAdapter
=============================================
package adapters;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.keshav.hideactionbarandfooterexample.R;
import java.util.List;
/*
* RecyclerView Adapter that allows to add a header view.
* */
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_HEADER = 2;
private static final int TYPE_ITEM = 1;
private List<String> mItemList;
public RecyclerAdapter(List<String> itemList) {
mItemList = itemList;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
if (viewType == TYPE_ITEM) {
final View view = LayoutInflater.from(context).inflate(R.layout.recycler_item, parent, false);
return RecyclerItemViewHolder.newInstance(view);
} else if (viewType == TYPE_HEADER) {
final View view = LayoutInflater.from(context).inflate(R.layout.recycler_header, parent, false);
return new RecyclerHeaderViewHolder(view);
}
throw new RuntimeException("There is no type that matches the type " + viewType + " + make sure your using types correctly");
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
if (!isPositionHeader(position)) {
RecyclerItemViewHolder holder = (RecyclerItemViewHolder) viewHolder;
String itemText = mItemList.get(position - 1); // header
holder.setItemText(itemText);
}
}
public int getBasicItemCount() {
return mItemList == null ? 0 : mItemList.size();
}
#Override
public int getItemViewType(int position) {
if (isPositionHeader(position)) {
return TYPE_HEADER;
}
return TYPE_ITEM;
}
#Override
public int getItemCount() {
return getBasicItemCount() + 1; // header
}
private boolean isPositionHeader(int position) {
return position == 0;
}
}
=====================================================
RecyclerHeaderViewHolder
=====================================================
package adapters;
import android.support.v7.widget.RecyclerView;
import android.view.View;
public class RecyclerHeaderViewHolder extends RecyclerView.ViewHolder {
public RecyclerHeaderViewHolder(View itemView) {
super(itemView);
}
}
=====================================================
RecyclerItemViewHolder
=====================================================
package adapters;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import com.keshav.hideactionbarandfooterexample.R;
public class RecyclerItemViewHolder extends RecyclerView.ViewHolder {
private final TextView mItemTextView;
public RecyclerItemViewHolder(final View parent, TextView itemTextView) {
super(parent);
mItemTextView = itemTextView;
}
public static RecyclerItemViewHolder newInstance(View parent) {
TextView itemTextView = (TextView) parent.findViewById(R.id.itemTextView);
return new RecyclerItemViewHolder(parent, itemTextView);
}
public void setItemText(CharSequence text) {
mItemTextView.setText(text);
}
}
===================================================
activity_main.xml
===================================================
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"/>
<ImageButton
android:id="#+id/fabButton"
android:layout_width="56dp"
android:layout_height="56dp"
android:layout_gravity="bottom|right"
android:layout_marginBottom="16dp"
android:layout_marginRight="16dp"
android:background="#drawable/fab_bcg"
android:src="#drawable/ic_favorite_outline_white_24dp"
android:contentDescription="#string/fab_description"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar_bottom"
android:layout_width="match_parent"
android:layout_alignParentBottom="true"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"/>
</RelativeLayout>
</FrameLayout>
==================================================
recycle_header.xml in layout folder
==================================================
<?xml version="1.0" encoding="utf-8"?>
<View xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"/>
==================================================
recycle_item.xml in layout folder
==================================================
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="8dp"
card_view:cardCornerRadius="4dp">
<TextView
android:id="#+id/itemTextView"
android:layout_width="match_parent"
android:layout_height="?attr/listPreferredItemHeight"
android:gravity="center_vertical"
android:padding="8dp"
style="#style/Base.TextAppearance.AppCompat.Body2"/>
</android.support.v7.widget.CardView>
=================================================
styles.xml
=================================================
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
</style>
<style name="AppThemeRed" parent="AppTheme">
<item name="colorPrimary">#color/color_primary_red</item>
<item name="colorPrimaryDark">#color/color_primary_red_dark</item>
</style>
<style name="AppThemeGreen" parent="AppTheme">
<item name="colorPrimary">#color/color_primary_green</item>
<item name="colorPrimaryDark">#color/color_primary_green_dark</item>
</style>
<style name="AppThemeBlue" parent="AppTheme">
<item name="colorPrimary">#color/color_primary_blue</item>
<item name="colorPrimaryDark">#color/color_primary_blue_dark</item>
<item name="colorAccent">#color/color_accent_pink</item>
</style>
</resources>
build.gradle Dependency
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:recyclerview-v7:25.3.1'
compile 'com.android.support:cardview-v7:25.3.1'
compile 'com.android.support:design:25.3.1'
#k0sh gave a fine solution. I want to update it to get a smooth animation
while showing and hiding the layout. Replace complete code inside
onNestedPreScroll() with the below code:
if (dy > 0) {
CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) child.getLayoutParams();
int viewBottomMargin = layoutParams.bottomMargin;
child.animate().translationY(child.getHeight() + viewBottomMargin).setInterpolator(new LinearInterpolator()).start();
} else if (dy < 0) {
child.animate().translationY(0).setInterpolator(new LinearInterpolator()).start();
}
#k0sh's QuickReturnFloaterBehavior works but it sometimes not listen to the slight scrolls.
I am having contents in NestedScrollView with a LinearLayout as a bottom bar & didn't have the recycler view. so, I can't use other suggested answers.
Those who are having the same situation can use the BottomNavigationBehavior from this post Bottom Navigation Behavior. it works perfectly & useful.
When the current top-level view has a scrolling content, the bottom
navigation should hide when it is scrolled down and retract back when
the content is scrolled up. For this purpose, we need to be aware of
the direction of the scroll. VerticalScrollingBehavior is a generic
layout behavior that it is somehow an extension to the
CoordinatorLayout.Behavior that dispatches events on for direction of
scrolling.
source code for BottomNavigationBehavior - https://gist.github.com/NikolaDespotoski/1d6fef4949eb9be05a46#file-bottomnavigationbehavior-java
snippet from BottomNavigationBehavior
#Override
public void onDirectionNestedPreScroll(CoordinatorLayout coordinatorLayout, V child, View target, int dx, int dy, int[] consumed, #ScrollDirection int scrollDirection) {
handleDirection(child, scrollDirection);
}
#Override
protected boolean onNestedDirectionFling(CoordinatorLayout coordinatorLayout, V child, View target, float velocityX, float velocityY, #ScrollDirection int scrollDirection) {
handleDirection(child, scrollDirection);
return true;
}
private void handleDirection(V child, #ScrollDirection int scrollDirection) {
if (!scrollingEnabled) return;
if (scrollDirection == ScrollDirection.SCROLL_DIRECTION_DOWN && hidden) {
hidden = false;
animateOffset(child, 0);
} else if (scrollDirection == ScrollDirection.SCROLL_DIRECTION_UP && !hidden) {
hidden = true;
animateOffset(child, child.getHeight());
}
}

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