gridview images with different alignment - android

I need to do something like this . It is similar to staggered gridview but all image has same dimension . How do i do this ?

Finally got it . The trick is to use staggered gridview of spancount 2 and have the second and last image to be of different height then all other . Here is an example .
First get the screen width .
WindowManager wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
screenWidth = size.x;
Now set the images in onBindViewHolder .
public void onBindViewHolder(final CustomRecycleViewHolder holder, final int position) {
final Holder myHolder = (Holder) holder;
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(images.get(position), opts);
opts.inJustDecodeBounds = false;
int height;
if (position == 1 || position == (images.size() - 1)) {
height = 150;
} else {
height = 300;
}
Picasso.with(activity)
.load(images.get(position))
.error(R.drawable.ic_empty)
.placeholder(R.drawable.ic_launcher)
.resize(screenWidth / 2, height)
.centerCrop()
.into((myHolder.images));
}
Result

Related

Alternative approach for ExpandableListView

I am designing a form which has part expandable groups and part generic form elements. When we uncollapse the group, an individual form is displayed.
I have tried with ExpandableListView but there are too many files that needs to be created. We have four tabs and each should have its own expandable list. What could be the alternative way to handle this?
The view I am expecting looks something like this: (ofcourse we have four tabs and each should have this view).
That's how I solved my problem. You have to change the static values. I hope it works.
#Override
public void onClick(View view) {
ViewHolder holder = (ViewHolder) recyclerView.findViewHolderForAdapterPosition(selectedItem);
if (holder != null) {
holder.expandButton.setSelected(false);
holder.expandableLayout.collapse();
}
int position = getAdapterPosition();
//dynamic Listview Height calculate start
float scale = view.getContext().getResources().getConfiguration().fontScale;
int hh = 0;
try {
WindowManager wm = (WindowManager) view.getContext().getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
int width = display.getWidth(); // deprecated
int height = display.getHeight(); // deprecated
View childView = listdetail.getAdapter().getView(0, null, listdetail);
childView.measure(UNBOUNDED, UNBOUNDED);
hh=childView.getMeasuredHeight();
} catch (Exception e) {
e.printStackTrace();
}
int scl = (int)(scale * (12f));
scl = scl<=0?1:scl;
ViewGroup.LayoutParams params = listdetail.getLayoutParams();
if(hh<=0) {
params.height = 10 * (listdetail.getAdapter().getCount()) * scl;
}
else {
params.height = (int) (((scale<0f?1f:1f) *hh * (listdetail.getAdapter().getCount()))+10);
}
listdetail.setLayoutParams(params);
//dynamic Listview Height calculate stop
if (position == selectedItem) {
selectedItem = UNSELECTED;
} else {
expandButton.setSelected(true);
expandableLayout.expand();
selectedItem = position;
}
}

Get Screen width and height on android 2.2

How I can get screen width and height for use this value on device with android version 2.2(API lv8).
I use this code:
public static Point Maximum(Context context)
{
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
int width = display.getWidth(); // deprecated
int height = display.getHeight(); // deprecated
Point temp=new Point();
return temp;
}
And when i want check by print Max point to textview:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView txt= (TextView)findViewById(R.id.text1);
txt.setText(Math.Maximum(this).toString());
}
Point is (0,0). What problem?
Try this code. But this API is deprecated in the new SDK versions you can use this.
Display display = activity.getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
Get Device Width and Height, return as point. Hope u like this.
public static Point Maximum(){
Display display = activity.getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
Point temp=new Point();
temp.set(width, height);
return temp;
}
Try this code:
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
Try this for getting your screen width. Similarly you can get screen height or can customize the same for returning both in a single function.
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
private int getScreenWidth() {
int width = 400;
int height = 600; // just intialising it to default value in case if there is any problem getting screen width
WindowManager wm = (WindowManager) activity // activity is the context if you are using this method in adapter. Otherwise in Activity you can simply ignore this
.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
if (android.os.Build.VERSION.SDK_INT >= 13) {
Point size = new Point();
display.getSize(size);
width = size.x;
height = size.y;
} else {
width = display.getWidth();
height= display.getHeight();
}
return width;//or height
}

Loading images using web service and Picasso, how to add inSampling size?

I am using Picasso library to load and display images in a ViewPager. The images being loaded have high resolution, I would like to add an insampling size to them. I do not know, however, how or where I should add this insampling size attribute. My ViewPagerAdapter.java class has the following.
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView iv_page_image;
inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.viewpager_item, container,false);
iv_page_image = (ImageView) itemView.findViewById(R.id.iv_page_image);
String path = pageList.get(position).getPageImage();
path = path.replaceAll(" ", "%20");
if (path != null && !(path.equalsIgnoreCase(""))) {
Picasso.with(mContext).load(path)
.placeholder(R.drawable.placeholder_empty)
.into(iv_page_image, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
}
});
}
((ViewPager) container).addView(itemView);
return itemView;
}
I would like to add something like the following to the images
private static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round((float) height
/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will
// guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
Just add .fit() to your call to Picasso and it will automatically calculate the appropriate inSampleSize to use when decoding the image.
You will also probably want to use either .centerInside() or .centerCrop() to ensure the aspect ratio of the image is not altered when automatically resized.

Setting ImageView' s size by phone screen size

i want ImageView's to look same on different screen sizes. To make it easier for you to understand how it should look there are some image:
Biggest problem is that my imageViews are created programmatically. ImageViews layout and size are set by this code
LinearLayout LinearLayoutas = (LinearLayout)findViewById(R.id.LinearLayout);
ImageView ImageViewas = new ImageView(this);
ImageViewas.setScaleType(ImageView.ScaleType.FIT_CENTER);
LinearLayoutas.setGravity(Gravity.CENTER);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
ImageViewas.setLayoutParams(params);
ImageViewas.getLayoutParams().height = 650;
ImageViewas.getLayoutParams().width = 950;
params.setMargins(0, 50, 0, 0);
Any ideas how to change this code that my app can look same on diffrent screen sizes?
Well, you can retrieve device resolution and set imageView width and height. Here is the solution.
private class ScreenResolution {
int width;
int height;
public ScreenResolution(int width, int height) {
this.width = width;
this.height = height;
}
}
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
ScreenResolution deviceDimensions() {
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
// getsize() is available from API 13
if (currentapiVersion >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
return new ScreenResolution(size.x, size.y);
}
else {
Display display = getWindowManager().getDefaultDisplay();
// getWidth() & getHeight() are deprecated
return new ScreenResolution(display.getWidth(), display.getHeight());
}
}
..................
LinearLayout LinearLayoutas = (LinearLayout)findViewById(R.id.LinearLayout);
ImageView ImageViewas = new ImageView(this);
ImageViewas.setScaleType(ImageView.ScaleType.FIT_CENTER);
LinearLayoutas.setGravity(Gravity.CENTER);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
ScreenResolution screenRes = deviceDimensions();
ImageViewas.setLayoutParams(params);
ImageViewas.getLayoutParams().height = screenRes.height;
ImageViewas.getLayoutParams().width = screenRes.width;
params.setMargins(0, 50, 0, 0);
Also when the device orientation will be changed, the width and height should be swapped. You can do that in onConfigurationChanged:
#Override
public void onConfigurationChanged(Configuration newConfiguration) {
super.onConfigurationChanged(newConfiguration);
// swap device width and height here and re-assign
}

Android: How to make a gridview of equal proportions within the Java code

I am working on an application which has a main screen with a gridview layout.
As it stands currently, I am hardcoding in DP numbers for the height and width of the boxes, which I obviously do not want to do. How to I create code that will determine the users' screen size and match the boxes accordingly so that someone with a large phone like a note will view the same thing as someone on a droid mini? IE, when hardcoding to 500dp on each side, it looks like this:
But my goal is to make it look like this on every screen size:
Currently, this is the Java code I have:
public class ActivityAdapter extends BaseAdapter {
//Array of Icons that will be used as menu choices
public static int[] imageOptions = {
R.drawable.vacation_quota, //Position 0
R.drawable.revenue_deficit, //Position 1
//+ many more options...
};
private Context context;
//Constructor to pass context back to Main class
public ActivityAdapter(Context applicationContext) {
context = applicationContext;
}
//Number of elements to be displayed on the grid
#Override
public int getCount() {
return imageOptions.length;
}
#Override
public View getView(int position, View convertView, ViewGroup arg2) {
ImageView iv;
if(convertView != null){
iv = (ImageView) convertView;
} else {
iv = new ImageView(context);
//Here I have it hard coded to match a 480px width. Here is where I need to change it, just not sure how
iv.setLayoutParams(new GridView.LayoutParams(240, 240));
iv.setScaleType(ScaleType.CENTER_CROP); //Center the cropping
}
//Sets the image to correspond to its position within the array.
iv.setImageResource(imageOptions[position]);
return iv;
}
Any ideas? I think logically I want to figure out the screen dimensions and use them to make the image dimensions match, just not sure how. Research from other threads has not helped a great deal so hoping I can get a simpler answer here with code posting.
You should get the screen width and height. Then use these values to dynamically set height and width for each cell
Try this code-
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle state) {
setContentView(new ViewGroup(this) {
private RelativeLayout[] items = new RelativeLayout[9];
private int width, height, itemWidth, itemHeight;
{
Random r = new Random();
for (int i = 0; i < 9; i++) {
items[i] = new RelativeLayout(getContext());
float[] hsv = new float[] {360 * r.nextFloat(), .50f, .75f};
items[i].setBackgroundColor(Color.HSVToColor(hsv));
addView(items[i]);
// UPDATE ////////////////////////////////////
ImageView image = new ImageView(getContext());
switch (i) {
case 0: // top left
case 1: // top center
case 2: // top right
case 3: // center left
case 4: // center center
case 5: // center right
case 6: // bottom left
case 7: // bottom center
case 8: // bottom right
image.setImageResource(R.drawable.ic_launcher);
break;
}
image.setScaleType(ScaleType.FIT_XY);
image.setLayoutParams(new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT
));
items[i].addView(image);
//////////////////////////////////////////////
}
}
#Override
protected void onMeasure(int wMS, int hMS) {
width = MeasureSpec.getSize(wMS);
height = MeasureSpec.getSize(hMS);
itemWidth = width / 3;
itemHeight = height / 3;
wMS = MeasureSpec.makeMeasureSpec(itemWidth, MeasureSpec.EXACTLY);
hMS = MeasureSpec.makeMeasureSpec(itemHeight, MeasureSpec.EXACTLY);
measureChildren(wMS, hMS);
setMeasuredDimension(width, height);
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
for (int i = 0; i < 9; i++) {
l = itemWidth * (i % 3);
t = itemHeight * (i / 3);
r = l + itemWidth;
b = t + itemHeight;
items[i].layout(l, t, r, b);
}
}
});
super.onCreate(state);
}
}
Output-
Edit-
For creating scrollable grid view see this http://www.androidhive.info/2012/02/android-gridview-layout-tutorial/
I ended up not able to use some of the recommendations here and had to use a deprecated method to retain my app structure. The code specifically that was added to mine was:
iv = new ImageView(context);
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
float width2 = display.getWidth();
int length = (int) (width2/2);
iv.setLayoutParams(new GridView.LayoutParams(length, length));
With this, the height and width would crop to the right size depending on the size of the screen.

Categories

Resources