Categories
discuss

Fit Image into grid view

I am trying to fit the image into gridview. But I don’t understand from where my gridview is getting the height of the view.

The cell of the grid view is smaller than the image. I want to display the image full in a cell. But I don’t want to hard code the size of the ImageView.

My codes

gridView in xml

<GridView
    android:id="@+id/gridview_movie_list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_gravity="center"
    android:numColumns="auto_fit"
    android:columnWidth="185dp"
    android:stretchMode="columnWidth"/>

My ImageView which I am inflating.

 <ImageView
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:scaleType="centerCrop"/>

And my getView method in my adapter class

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(
            mContext.LAYOUT_INFLATER_SERVICE);
    ImageView imageView;

    if (convertView == null) {
        imageView = (ImageView) inflater.inflate(R.layout.grid_view_item, null);
    } else {
        imageView = (ImageView) convertView;
    }

    Picasso.with(mContext).setLoggingEnabled(false);
    Picasso.with(mContext)
            .load(imageResource[position])
            .into(imageView);

    return imageView;
}

This is what I get

This is what I get

And this is what is required

enter image description here

Answer

What worked for me was adding this line to my image view xml.

android:adjustViewBounds="true"

Now my output is just like what I wanted. Thanks for the help every one

Categories
discuss

Java – store objects in a hierarchy that follows their class inheritance

I need to store lots of objects that belong to different classes:

ClassA {...}
ClassA1 extends ClassA {...}
ClassA2 extends ClassA {...}
ClassA2a extends ClassA2 {...}
ClassB {...}

Now I need to find a way to store all these objects in a way that allows me to efficiently get all objects that belong to a particular class and its inherited child classes. For example, this imaginary code

getObjects(ClassA2)

would return a list of all stored objects that belong to ClassA2 or ClassA2a.

I believe a tree collection of some sort would be suitable, but I can’t think of any way to implement it. Any ideas?


(Background: I am creating a simple java game, in which there’s number of sprites that I need to manage, while some of those sprites share similar properties. When I check for events like collisions, I need to get all objects that extend EnemySprite and compare their coordinates with the player’s sprite.)

Answer

Mifeet seems to have literally answered your question, but I suspect you shouldn’t be trying to do what you’re proposing to do. Why not just have a master list of all objects that might collide, then filter it as needed using instanceof?

This is conceptually a lot easier than what you’re proposing to do, and the efficiency impact probably isn’t that big. (In general, you will probably hear or have heard the mantra: Don’t try to optimize too early.)

To be honest, I’m not sure you realize that filtering for EnemySprite will get you all object instances of its subclasses as well.

public class CollisionChecker(){

   private List colliders;

   public CollisionChecker(){    
       colliders = new ArrayList<Object>();    
   }

   public void addCollider(Object o){
       colliders.add(o);
   }

   public List<EnemySprite> getEnemySprites(){
       List<EnemySprite> enemies = new ArrayList<EnemySprite>();
       for (Object o : colliders)
           if (o instanceof EnemySprite)
               enemies.add((EnemySprite)o);
       return enemies;        
   }     
}
Categories
discuss

Bind ButterKnife to Dialog fails

I try to bind ButterKnife to a AleterDialog that i made with a DialogBuilder method And exist this method ButterKnife.bind(Object,Dialog); but dosen’t work for me

import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
public class NewUserDialogFragment extends DialogFragment {
    @Bind(R.id.textuserAccount)
    EditText textuserAccount;
    @Bind(R.id.textPassword)
    EditText textPassword;
    @Bind(R.id.nauta_domains)
    Spinner nauta_domains;
    @Bind(R.id.manualConfig)
    View manualConfig;
    @Bind(R.id.checkViewPass)
    CheckBox checkViewPass;

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        AlertDialog dialog = new AlertDialog.Builder(getActivity())
                .setIcon(R.drawable.new_user_dialog__icon)
                .setTitle(R.string.new_user_dialog_title)
                .setView(R.layout.accountlist_dialog_user_)
                .setPositiveButton(R.string.alert_dialog_create, void_OnClickListener)
                .setNegativeButton(R.string.alert_dialog_cancel, void_OnClickListener)
                .create();
      //Fails!!!!!!!
        ButterKnife.bind(this,dialog);  
    ...

ERROR:

Caused by: java.lang.IllegalStateException: Required view 'textuserAccount' with ID 2131624044 for field 'textuserAccount' was not found. If this view is optional add '@Nullable' annotation.
                                                                                      at butterknife.ButterKnife$Finder.findRequiredView(ButterKnife.java:140)

and textuserAccount = (EditText) ((Dialog) dialog).findViewById(R.id.textuserAccount); works perfectly

I can use butterknife somehow in this class?

Answer

You need to inflate your dialog layout and pass the resulting View object to butterknife.

    view = View.inflate(getContext(), R.layout.accountlist_dialog_user_, null);
    ButterKnife.bind(this, view);

At least, that’s how I’ve used Butterknife in dialogs and it works fine for me.

Categories
discuss

Determine which day of week is each date of the month

I want to create a calendar with Java 8. So far I have this:

YearMonth yearMonthObject = YearMonth.of(year, month);
int daysOfCurrentMonth = yearMonthObject.lengthOfMonth();

int i = 1;
ArrayList<Integer> Dayes = new ArrayList<Integer>();
for(i=1; i<=daysOfCurrentMonth; i++){
    Dayes.add(i);
}

Dayes.forEach(value -> System.out.print(value));

which prints the days of the current month (for example May).

How can I determine that 1 is Sunday, 2 is Monday, 3 is Tuesday, …, 8 is Sunday (next week), etc.?

Answer

You have a YearMonth object. For each day of the month, you can call atDay(dayOfMonth) to return a LocalDate at that specific day of month. With that LocalDate, you can then call:

As such, you should change your Dayes list to hold LocalDates instead of Integers, and then you can have, for example:

YearMonth yearMonthObject = YearMonth.of(year, month);
int daysOfCurrentMonth = yearMonthObject.lengthOfMonth();

ArrayList<LocalDate> dayes = new ArrayList<LocalDate>();
for(int i = 1; i <= daysOfCurrentMonth; i++){
    dayes.add(yearMonthObject.atDay(i));
}

dayes.forEach(value -> System.out.println(value.getDayOfMonth() + " " + value.getDayOfWeek()));

This will print each day of that month followed by the corresponding day of the week.

As a side-note, you can get a real display value for the day of week (instead of the name() of the enum like above) by calling getDisplayName(style, locale). The style represents how to write the days (long form, short form…) and the locale is the locale to use for the display name. An example would be:

value.getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.ENGLISH)

which would output the full text of the day of the week in English. Sample output for 04/2016 with the above change:

1 Friday
2 Saturday
3 Sunday
4 Monday
5 Tuesday
Categories
discuss

How do I supplant jQuery’s toggleClass method with pure JavaScript?

How can I turn this piece of jQuery code into JavaScript?

$('#element').click(function(){
    $(this).toggleClass('class1 class2')
});

I have already tried the following pieces of code, but to no avail.

First one is:

var element = document.getElementById('element'),
    classNum = 0; // Supposing I know that the first time there will be that class
element.onmousedown = function() {
    if (classNum === 0) {
        this.classList.remove("class1");
        this.classList.add("class2");
        classNum = 1;
    }
    else if (classNum === 1) {
        this.classList.remove("class2");
        this.classList.add("class1");
        classNum = 0;
    }
}

Second one is:

var element = document.getElementById('element'),
    classNum = 0; // Supposing I know that the first time there will be that class
element.onmousedown = function() {
    if (classNum === 0) {
        this.className -= "class1";
        this.classList += "class2";
        classNum = 1;
    }
    else if (classNum === 1) {
        this.classList -= "class2";
        this.classList += "class1";
        classNum = 0;
    }
}

Any answer that doesn’t suggest that I stick with jQuery will be greatly appreciated.

[EDIT]

I’ve tried all of your solutions, but haven’t been able to get it right. I believe it’s because I didn’t state clearly that the element has multiple classes like so:

class="class1 class3 class4"

And what I want is basically to replace class1 with class2 and toggle between them.

Answer

Update: In response to comments, classList.toggle is a pure javascript solution. It has nothing to do with jQuery as one comment implies. If there is a requirement to support old versions of IE then there is a shim (pollyfill) at the MDN link below. And this shim, if needed, is far superior to the accepted answer.

Using classList.toggle certainly seems like the simplest solution. Also see Can I Use classList for browser support.

element.onclick = function() {
  'class1 class2'.split(' ').forEach(function(s) {
      element.classList.toggle(s);
  });
}

Run the snippet to try

box.onclick = function() {
  'class1 class2'.split(' ').forEach(function(s) {
    box.classList.toggle(s);
    stdout.innerHTML = box.className;
  });
}


/* alternative 
box.onclick = function() {
  ['class1', 'class2'].forEach(function(s) {
    box.classList.toggle(s);
    stdout.innerHTML = box.className;
  });
}
*/
.class1 { background-color: red;}
.class2 { background-color: blue;}
.class3 { width: 100px; height: 100px; border: 1px black solid;}
click me:
<div id="box" class="class1 class3"></div>

<div id="stdout"></div>
Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..