问:
Adding your own custom attribute in android xml
I am having a problem using vector drawables, although I found out that you can support vector by using the

```<code>app:srcCompat:"@/drawable/your_icon"
</code>```

and this works fine, but I want to put the icon on top of the text of a button, but I can't use the drawableTop attribute on my button. So is creating custom attribute possible?

答:
Try this.

```<code>public class CustomButtonForDrawableTop extends AppCompatButton{
public CustomButtonForDrawableTop(Context context){
    super(context);
}

public CustomButtonForDrawableTop(Context context, AttributeSet attrs){
    super(context,attrs);
    initAttrs(context,attrs);
}

public CustomButtonForDrawableTop(Context context, AttributeSet attrs, int defStyleAttr){
    super(context,attrs,defStyleAttr);
    initAttrs(context,attrs);
}

void initAttrs(Context context, AttributeSet attrs) {
    if(attrs != null){
        TypedArray attributeArray = context.obtainStyledAttributes(
                attrs,
                R.styleable.CustomButtonForDrawableTop);

        Drawable drawableTop = null;

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
            drawableTop = attributeArray.getDrawable(R.styleable.CustomButtonForDrawableTop_drawableTopCompat);
        } else {
            final int drawableTopId =attributeArray.getResourceId(R.styleable.CustomButtonForDrawableTop_drawableTopCompat, -1);

            if(drawableTopId != -1)
                drawableTop = AppCompatResources.getDrawable(context,drawableTopId);
        }
        setCompoundDrawablesWithIntrinsicBounds(null, drawableTop, null, null);
        attributeArray.recycle();
    }
}
}
</code>```

then create attrs.xml on values

```<code><resources>
<declare-styleable name="CustomButtonForDrawableTop">
    <attr name="drawableTopCompat" format="reference"/>
</declare-styleable>
</resources>
</code>```

here's how you call it

```<code> <com.example.user.project.CustomButtonForDrawableTop
            app:drawableTopCompat="@drawable/ic_people_black_48px"
            android:layout_margin="5dp"
            android:drawableTint="@color/myColor"
            android:id="@+id/btnStaff"
            android:layout_width="115dp"
            android:layout_height="115dp"
            android:elevation="4dp"
            android:text="Staff"
            android:textAllCaps="false"
            android:textColor="@color/myColorWhite"
            android:shadowColor="@color/myColorActionBar"
            android:background="@drawable/custom_button_rounded8"
            app:layout_flexBasisPercent="@fraction/fraction48percent"/>
</code>```

Body:
I am having a problem using vector drawables, although I found out that you can support vector by using the

app:srcCompat:"@/drawable/your_icon"

and this works fine, but I want to put the icon on top of the text of a button, but I can't use the drawableTop attribute on my button. So is creating custom attribute possible?

Body:
Try this.

public class CustomButtonForDrawableTop extends AppCompatButton{
public CustomButtonForDrawableTop(Context context){
    super(context);
}

public CustomButtonForDrawableTop(Context context, AttributeSet attrs){
    super(context,attrs);
    initAttrs(context,attrs);
}

public CustomButtonForDrawableTop(Context context, AttributeSet attrs, int defStyleAttr){
    super(context,attrs,defStyleAttr);
    initAttrs(context,attrs);
}

void initAttrs(Context context, AttributeSet attrs) {
    if(attrs != null){
        TypedArray attributeArray = context.obtainStyledAttributes(
                attrs,
                R.styleable.CustomButtonForDrawableTop);

        Drawable drawableTop = null;

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
            drawableTop = attributeArray.getDrawable(R.styleable.CustomButtonForDrawableTop_drawableTopCompat);
        } else {
            final int drawableTopId =attributeArray.getResourceId(R.styleable.CustomButtonForDrawableTop_drawableTopCompat, -1);

            if(drawableTopId != -1)
                drawableTop = AppCompatResources.getDrawable(context,drawableTopId);
        }
        setCompoundDrawablesWithIntrinsicBounds(null, drawableTop, null, null);
        attributeArray.recycle();
    }
}
}

then create attrs.xml on values

<resources>
<declare-styleable name="CustomButtonForDrawableTop">
    <attr name="drawableTopCompat" format="reference"/>
</declare-styleable>
</resources>

here's how you call it

 <com.example.user.project.CustomButtonForDrawableTop
            app:drawableTopCompat="@drawable/ic_people_black_48px"
            android:layout_margin="5dp"
            android:drawableTint="@color/myColor"
            android:id="@+id/btnStaff"
            android:layout_width="115dp"
            android:layout_height="115dp"
            android:elevation="4dp"
            android:text="Staff"
            android:textAllCaps="false"
            android:textColor="@color/myColorWhite"
            android:shadowColor="@color/myColorActionBar"
            android:background="@drawable/custom_button_rounded8"
            app:layout_flexBasisPercent="@fraction/fraction48percent"/>


来源: stackexchange

问:
Why does the enqueued owl carousel work with the NewsMag Pro theme version, and not with the default WordPress Installation?
I am trying to write and submit a new WordPress plugin, and I have the goals of needing the plugin to show a "snippet" of our main site newyorkbusinessreview.com including our books selection and also some of our published journal articles which are featured in carousel sliders.  I checked the HTML code using Firefox and Shift-Control-C in the originalnewyorkbusinessreview.com site, and the carousel sliders are based on the owl carousel, but probably not the latest version.  (See owlcarousel2.github.io/OwlCarousel2/demos/demos.html for the demonstration page for the  owlcarousel2 latest documentation for the latest version of the Owl Carousel Slider.)

Consulting with the Site Editor, it is very important that our plugin "fits very nicely" wherever it is posted.  However, the same HTML code renders one way on one page and another way on the next, with the theme page working of course fine and a fresh install of WordPress 4.7.5 (just downloaded from the WordPress site) does not.  I only added in one plugin on the fresh WordPress 4.7.5 (being the amr-shortcode-any-widget, a very nice plugin that allows widgets to be directly placed on a page) to test it.

I was advised by WordPress plugin review to use wp_enqueue_style and so forth to enqueue everything properly.  I found the part of the main theme that did this (it was in one file, enqueue.php) and I updated it as posted below.

Because there is a lot of code here already, and those skilled in WordPress can access the relevant files knowing the main web url, for "brevity" I have not put here additional code.  But if requested, of course I can of course update it.  Also within Firefox Shift-Control-C can be used to view specific elements at each web-site code directly.

So why does it work with the NewsMag Pro theme version, and not with the default WordPress Installation?

Any ideas?

Test Page - Fresh Install Plugin Output That Does Not Work (See:  http://support.issues.owl.newyorkbusinessreview.com/wordpress/test-page/ )

Image Showing Carousel Not Working (click link to view)

       Books, Magazines, and Journals

      VIEW ALL

        Books, Magazines, and Journals

       The Seven Secrets of Influence…

        April 24, 2017        0

        Books, Magazines, and Journals

       HBR Essentials and Two Complementary…

        April 23, 2017        0

        Books, Magazines, and Journals

       Harvard Business Review Magazine

        April 23, 2017        0

        Books, Magazines, and Journals

       HBR’s 10 Must Reads

        April 23, 2017        0

        Books, Magazines, and Journals

       Aiming at Amazon: The NEW…

        April 19, 2017        0

        Books, Magazines, and Journals

       Latest Business Books

        April 6, 2017        0

```
</div>
</div>
</p>

<h3>My Modified Equenes.php -- Added Header (See: carousel_edit_url_for_newspro/enqueues.php in the themes directory)</h3>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?php

/**
 * Enqueue scripts and styles in the frontend.
 */
function corrected_newsmag_scripts() {
 $corrected_newsmag = wp_get_theme();

 /**
  * Load Google Fonts
  */
  /*
 wp_enqueue_style( 'newsmag-fonts', '//fonts.googleapis.com/css?family=Lato:100,300,400,700,900|Poppins:400,500,600,700', array(), $newsmag['Version'], 'all' );
   */
 wp_enqueue_style( 'CEU_newsmag-fonts', '//fonts.googleapis.com/css?family=Lato:100,300,400,700,900|Poppins:400,500,600,700', array(), false, 'all' );

 wp_enqueue_style( 'CEU_font-awesome-style', plugin_dir_path( __FILE__ )  . '/assets/vendors/fontawesome//font-awesome.min.css' );

 /**
  * Load the bootstrap framework
  */
 wp_enqueue_style( 'CEU_bootstrap-style', plugin_dir_path( __FILE__ )  . '/assets/vendors/bootstrap/bootstrap.min.css' );
 wp_enqueue_style( 'CEU_bootstrap-theme-style', plugin_dir_path( __FILE__ )  . '/assets/vendors/bootstrap/bootstrap-theme.min.css' );
/*
 wp_enqueue_script( 'newsmag-bootstrap', plugin_dir_path( __FILE__ )  . '/assets/vendors/bootstrap/bootstrap.min.js', array( 'jquery' ), $newsmag['Version'], true );
*/
 wp_enqueue_script( 'CEU_newsmag-bootstrap', plugin_dir_path( __FILE__ )  . '/assets/vendors/bootstrap/bootstrap.min.js', array( 'jquery' ), false, true );

 /**
  * Load offscreen helper
  */
  /*
 wp_enqueue_script( 'newsmag-offscreen', plugin_dir_path( __FILE__ )  . '/assets/vendors/offscreen/offscreen.min.js', array( 'jquery' ), $newsmag['Version'], true );
  */
 wp_enqueue_script( 'CEU_newsmag-offscreen', plugin_dir_path( __FILE__ )  . '/assets/vendors/offscreen/offscreen.min.js', array( 'jquery' ), false , true );

 /**
  * Load the Sticky library
  */
  /*
 wp_enqueue_script( 'newsmag-sticky', plugin_dir_path( __FILE__ )  . '/assets/vendors/sticky/jquery.sticky.js', array( 'jquery' ), $newsmag['Version'], true );
  */
 wp_enqueue_script( 'CEU_newsmag-sticky', plugin_dir_path( __FILE__ )  . '/assets/vendors/sticky/jquery.sticky.js', array( 'jquery' ), false, true );

 /**
  * Theme styling
  */

 wp_enqueue_style( 'CEU_newsmag-style', get_stylesheet_uri() );
/*
wp_enqueue_style( 'newsmag-stylesheet', plugin_dir_path( __FILE__ )  . '/assets/css/style.css', array(), $newsmag['Version'] );
*/
        wp_enqueue_style( 'CEU_newsmag-stylesheet', plugin_dir_path( __FILE__ )  . '/assets/css/style.css', array(), false );

 /**
  * Load menu script & skip-link-focus-fix
  */

 wp_enqueue_script( 'CEU_newsmag-navigation', plugin_dir_path( __FILE__ )  . '/assets/js/navigation.js', array(), $newsmag['Version'], true );
/*  Added CEU_ prefix and also set version to default (false)
 wp_enqueue_script( 'newsmag-skip-link-focus-fix', plugin_dir_path( __FILE__ )  . '/assets/js/skip-link-focus-fix.js', array(), $newsmag['Version'], true );
*/
 wp_enqueue_script( 'CEU_newsmag-skip-link-focus-fix', plugin_dir_path( __FILE__ )  . '/assets/js/skip-link-focus-fix.js', array(), false, true );

 /**
  * Adsense loader
  */
/* Old version, updated version and CEU_ prefix
 wp_enqueue_script( 'newsmag-adsense-loader', plugin_dir_path( __FILE__ )  . '/assets/vendors/adsenseloader/jquery.adsenseloader.js', array('jquery'), $newsmag['Version'], true );
*/

 wp_enqueue_script( 'CEU_newsmag-adsense-loader', plugin_dir_path( __FILE__ )  . '/assets/vendors/adsenseloader/jquery.adsenseloader.js', array('jquery'), false, true );

 /**
  *Load the theme's core Javascript
  */

 wp_enqueue_script( 'CEU_machothemes-object', plugin_dir_path( __FILE__ )  . '/assets/vendors/machothemes/machothemes.min.js', array(), $newsmag['Version'], true );
 wp_enqueue_script( 'CEU_newsmag-functions', plugin_dir_path( __FILE__ )  . '/assets/js/functions.js', array('jquery'), $newsmag['Version'], true );
wp_localize_script( 'CEU_newsmag-functions', 'WPUrls', array(
  'siteurl' => get_option( 'siteurl' ),
  'theme'   => get_template_directory_uri(),
  'ajaxurl' => admin_url( 'admin-ajax.php' )
 ) );

 if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
  wp_enqueue_script( 'CEU_comment-reply' );
 }

 /**
  * OwlCarousel Library
  */
  /*
 wp_enqueue_script( 'owlCarousel-js', plugin_dir_path( __FILE__ )  . '/assets/vendors/owl-carousel/owl.carousel.min.js', array( 'jquery' ), $corrected_newsmag['Version'], true );
  */
    wp_enqueue_script( 'CEU_owlCarousel-js',
     plugin_dir_path( __FILE__ )  . '/assets/vendors/owl-carousel/owl.carousel.min.js', array( 'jquery' ), false, true );

    wp_enqueue_style( 'CEU_owlCarousel-main-css', plugin_dir_path( __FILE__ )  . '/assets/vendors/owl-carousel/owl.carousel.min.css' );

    wp_enqueue_style( 'CEU_owlCarousel-theme-css', plugin_dir_path( __FILE__ )  . '/assets/vendors/owl-carousel/owl.theme.default.css' );

}

add_action( 'wp_enqueue_scripts', 'corrected_newsmag_scripts' );

/**
 * Load admin fonts
 */
/*
function corrected_newsmag_admin_scripts() {
 $newsmag = wp_get_theme();
 wp_enqueue_style( 'newsmag-fonts', 'https://fonts.googleapis.com/css?family=Lato:100,300,400,700,900|Poppins:400,500,600,700', array(), $newsmag['Version'], 'all' );
}

add_action( 'admin_enqueue_scripts', 'corrected_newsmag_admin_scripts' );
*/

/**
 * Load editor styles
 */
/*
function corrected_newsmag_add_editor_styles() {
 add_editor_style( 'inc/assets/css/custom-editor-style.css' );
}

add_action( 'admin_init', 'corrected_newsmag_add_editor_styles' );
*/</code>```

Original Page with the Newsmag Pro Theme That Works (See: http://support.issues.owl.newyorkbusinessreview.com/ )

Image Showing Carousel Working With NewsMag Pro Theme (click link to view)

      VIEW ALL

        Books, Magazines, and Journals

       The Seven Secrets of Influence…

        April 24, 2017        0

        Books, Magazines, and Journals

       HBR Essentials and Two Complementary…

        April 23, 2017        0

        Books, Magazines, and Journals

       Harvard Business Review Magazine

        April 23, 2017        0

        Books, Magazines, and Journals

       HBR’s 10 Must Reads

        April 23, 2017        0

        Books, Magazines, and Journals

       Aiming at Amazon: The NEW…

        April 19, 2017        0

        Books, Magazines, and Journals

       Latest Business Books

        April 6, 2017        0

prev

next

```

答:
The reasons it was not working were:
1)  The enqueue.php file did not properly load the content - plugin_dir_path( FILE ) was not correct.
2)  There was a conflict with the style sheets of the main theme and the style sheets of other themes.  Hence the CSS files needed to be updated.
3)  A custom token needed to be put at the beginning: CEU_newsmag-bootstrap for example.  That was in the existing code, but it was an earlier reason why the plugin did not work as intended.

Please submit questions to stephenelliott@newyorkbusinessreview.com

The plugin in the default Twenty-Seventeen Theme (with the additional WordPress plugin "amr shortcode any widget" used to place the widget on the page) can be seen at http://support.issues.owl.newyorkbusinessreview.com/ninja/test/

The corrected version of enqueue.php is below (with all the enqueue fixes):

<?php

/**
 * Enqueue scripts and styles in the frontend.
 */
function corrected_newsmag_scripts() {
 $corrected_newsmag = wp_get_theme();

 /**
  * Load Google Fonts
  */
  /*
 wp_enqueue_style( 'newsmag-fonts', '//fonts.googleapis.com/css?family=Lato:100,300,400,700,900|Poppins:400,500,600,700', array(), $newsmag['Version'], 'all' );
   */
 wp_enqueue_style( 'CEU_newsmag-fonts', '//fonts.googleapis.com/css?family=Lato:100,300,400,700,900|Poppins:400,500,600,700', array(), false, 'all' );

 wp_enqueue_style( 'CEU_font-awesome-style', plugin_dir_url( __FILE__ )  . '/assets/vendors/fontawesome//font-awesome.min.css' );

 /**
  * Load the bootstrap framework
  */
 wp_enqueue_style( 'CEU_bootstrap-style', plugin_dir_url( __FILE__ )  . '/assets/vendors/bootstrap/bootstrap.min.css' );
 wp_enqueue_style( 'CEU_bootstrap-theme-style', plugin_dir_url( __FILE__ )  . '/assets/vendors/bootstrap/bootstrap-theme.min.css' );
/*
 wp_enqueue_script( 'newsmag-bootstrap', plugin_dir_url( __FILE__ )  . '/assets/vendors/bootstrap/bootstrap.min.js', array( 'jquery' ), $newsmag['Version'], true );
*/
 wp_enqueue_script( 'CEU_newsmag-bootstrap', plugin_dir_url( __FILE__ )  . '/assets/vendors/bootstrap/bootstrap.min.js', array( 'jquery' ), false, true );

 /**
  * Load offscreen helper
  */
  /*
 wp_enqueue_script( 'newsmag-offscreen', plugin_dir_url( __FILE__ )  . '/assets/vendors/offscreen/offscreen.min.js', array( 'jquery' ), $newsmag['Version'], true );
  */
 wp_enqueue_script( 'CEU_newsmag-offscreen', plugin_dir_url( __FILE__ )  . '/assets/vendors/offscreen/offscreen.min.js', array( 'jquery' ), false , true );

 /**
  * Load the Sticky library
  */
  /*
 wp_enqueue_script( 'newsmag-sticky', plugin_dir_url( __FILE__ )  . '/assets/vendors/sticky/jquery.sticky.js', array( 'jquery' ), $newsmag['Version'], true );
  */
 wp_enqueue_script( 'CEU_newsmag-sticky', plugin_dir_url( __FILE__ )  . '/assets/vendors/sticky/jquery.sticky.js', array( 'jquery' ), false, true );

 /**
  * Theme styling
  */

 wp_enqueue_style( 'CEU_newsmag-style', get_stylesheet_uri() );
/*
wp_enqueue_style( 'newsmag-stylesheet', plugin_dir_url( __FILE__ )  . '/assets/css/style.css', array(), $newsmag['Version'] );
*/
        wp_enqueue_style( 'CEU_newsmag-stylesheet', plugin_dir_url( __FILE__ )  . '/assets/css/style.css', array(), false );

 /**
  * Load menu script & skip-link-focus-fix
  */

 wp_enqueue_script( 'CEU_newsmag-navigation', plugin_dir_url( __FILE__ )  . '/assets/js/navigation.js', array(), $newsmag['Version'], true );
/*  Added CEU_ prefix and also set version to default (false)
 wp_enqueue_script( 'newsmag-skip-link-focus-fix', plugin_dir_url( __FILE__ )  . '/assets/js/skip-link-focus-fix.js', array(), $newsmag['Version'], true );
*/
 wp_enqueue_script( 'CEU_newsmag-skip-link-focus-fix', plugin_dir_url( __FILE__ )  . '/assets/js/skip-link-focus-fix.js', array(), false, true );

 /**
  * Adsense loader
  */
/* Old version, updated version and CEU_ prefix
 wp_enqueue_script( 'newsmag-adsense-loader', plugin_dir_url( __FILE__ )  . '/assets/vendors/adsenseloader/jquery.adsenseloader.js', array('jquery'), $newsmag['Version'], true );
*/

 wp_enqueue_script( 'CEU_newsmag-adsense-loader', plugin_dir_url( __FILE__ )  . '/assets/vendors/adsenseloader/jquery.adsenseloader.js', array('jquery'), false, true );

 /**
  *Load the theme's core Javascript
  */

 wp_enqueue_script( 'CEU_machothemes-object', plugin_dir_url( __FILE__ )  . '/assets/vendors/machothemes/machothemes.min.js', array(), $newsmag['Version'], true );
 wp_enqueue_script( 'CEU_newsmag-functions', plugin_dir_url( __FILE__ )  . '/assets/js/functions.js', array('jquery'), $newsmag['Version'], true );
wp_localize_script( 'CEU_newsmag-functions', 'WPUrls', array(
  'siteurl' => get_option( 'siteurl' ),
  'theme'   => get_template_directory_uri(),
  'ajaxurl' => admin_url( 'admin-ajax.php' )
 ) );

 if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
  wp_enqueue_script( 'CEU_comment-reply' );
 }

 /**
  * OwlCarousel Library
  */
  /*
 wp_enqueue_script( 'owlCarousel-js', plugin_dir_url( __FILE__ )  . '/assets/vendors/owl-carousel/owl.carousel.min.js', array( 'jquery' ), $corrected_newsmag['Version'], true );
  */
    wp_enqueue_script( 'CEU_owlCarousel-js',
     plugin_dir_url( __FILE__ )  . '/assets/vendors/owl-carousel/owl.carousel.min.js', array( 'jquery' ), false, true );

    wp_enqueue_style( 'CEU_owlCarousel-main-css', plugin_dir_url( __FILE__ )  . '/assets/vendors/owl-carousel/owl.carousel.min.css' );

    wp_enqueue_style( 'CEU_owlCarousel-theme-css', plugin_dir_url( __FILE__ )  . '/assets/vendors/owl-carousel/owl.theme.default.css' );

}

add_action( 'wp_enqueue_scripts', 'corrected_newsmag_scripts' );

/**
 * Load admin fonts
 */
/*
function corrected_newsmag_admin_scripts() {
 $newsmag = wp_get_theme();
 wp_enqueue_style( 'newsmag-fonts', 'https://fonts.googleapis.com/css?family=Lato:100,300,400,700,900|Poppins:400,500,600,700', array(), $newsmag['Version'], 'all' );
}

add_action( 'admin_enqueue_scripts', 'corrected_newsmag_admin_scripts' );
*/

/**
 * Load editor styles
 */
/*
function corrected_newsmag_add_editor_styles() {
 add_editor_style( 'inc/assets/css/custom-editor-style.css' );
}

add_action( 'admin_init', 'corrected_newsmag_add_editor_styles' );
*/```

The CSS files that needed modification (according to the developer we hired at Code Ninjas) were:

Files with changes: – assets/sass/elements/lists.scss –
  assets/sass/site/secondary/_widget-recent-posts.scss –
  assets/css/style.css

These can be found in the standard plugins directory on the demonstration website referenced earlier.  If there are questions feel free to email me at stephenelliott@newyorkbusinessreview.com (which is fast - as I receive an alert about your message - and also a little more flexible in including reference links an pictures currently) or else go to the contact page on http://www.newyorkbusinessreview.com and leave a message there on the contact form page - see the menu link on the bottom of the home page of the site.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to write and submit a new WordPress plugin, and I have the goals of needing the plugin to show a "snippet" of our main site newyorkbusinessreview.com including our books selection and also some of our published journal articles which are featured in carousel sliders.  I checked the HTML code using Firefox and Shift-Control-C in the originalnewyorkbusinessreview.com site, and the carousel sliders are based on the owl carousel, but probably not the latest version.  (See owlcarousel2.github.io/OwlCarousel2/demos/demos.html for the demonstration page for the  owlcarousel2 latest documentation for the latest version of the Owl Carousel Slider.)

Consulting with the Site Editor, it is very important that our plugin "fits very nicely" wherever it is posted.  However, the same HTML code renders one way on one page and another way on the next, with the theme page working of course fine and a fresh install of WordPress 4.7.5 (just downloaded from the WordPress site) does not.  I only added in one plugin on the fresh WordPress 4.7.5 (being the amr-shortcode-any-widget, a very nice plugin that allows widgets to be directly placed on a page) to test it.

I was advised by WordPress plugin review to use wp_enqueue_style and so forth to enqueue everything properly.  I found the part of the main theme that did this (it was in one file, enqueue.php) and I updated it as posted below.

Because there is a lot of code here already, and those skilled in WordPress can access the relevant files knowing the main web url, for "brevity" I have not put here additional code.  But if requested, of course I can of course update it.  Also within Firefox Shift-Control-C can be used to view specific elements at each web-site code directly.

So why does it work with the NewsMag Pro theme version, and not with the default WordPress Installation?

Any ideas?

Test Page - Fresh Install Plugin Output That Does Not Work (See:  http://support.issues.owl.newyorkbusinessreview.com/wordpress/test-page/ )

Image Showing Carousel Not Working (click link to view)

       Books, Magazines, and Journals

      VIEW ALL

        Books, Magazines, and Journals

       The Seven Secrets of Influence…

        April 24, 2017        0

        Books, Magazines, and Journals

       HBR Essentials and Two Complementary…

        April 23, 2017        0

        Books, Magazines, and Journals

       Harvard Business Review Magazine

        April 23, 2017        0

        Books, Magazines, and Journals

       HBR’s 10 Must Reads

        April 23, 2017        0

        Books, Magazines, and Journals

       Aiming at Amazon: The NEW…

        April 19, 2017        0

        Books, Magazines, and Journals

       Latest Business Books

        April 6, 2017        0

My Modified Equenes.php -- Added Header (See: carousel_edit_url_for_newspro/enqueues.php in the themes directory)

<?php

/**
 * Enqueue scripts and styles in the frontend.
 */
function corrected_newsmag_scripts() {
 $corrected_newsmag = wp_get_theme();

 /**
  * Load Google Fonts
  */
  /*
 wp_enqueue_style( 'newsmag-fonts', '//fonts.googleapis.com/css?family=Lato:100,300,400,700,900|Poppins:400,500,600,700', array(), $newsmag['Version'], 'all' );
   */
 wp_enqueue_style( 'CEU_newsmag-fonts', '//fonts.googleapis.com/css?family=Lato:100,300,400,700,900|Poppins:400,500,600,700', array(), false, 'all' );

 wp_enqueue_style( 'CEU_font-awesome-style', plugin_dir_path( __FILE__ )  . '/assets/vendors/fontawesome//font-awesome.min.css' );

 /**
  * Load the bootstrap framework
  */
 wp_enqueue_style( 'CEU_bootstrap-style', plugin_dir_path( __FILE__ )  . '/assets/vendors/bootstrap/bootstrap.min.css' );
 wp_enqueue_style( 'CEU_bootstrap-theme-style', plugin_dir_path( __FILE__ )  . '/assets/vendors/bootstrap/bootstrap-theme.min.css' );
/*
 wp_enqueue_script( 'newsmag-bootstrap', plugin_dir_path( __FILE__ )  . '/assets/vendors/bootstrap/bootstrap.min.js', array( 'jquery' ), $newsmag['Version'], true );
*/
 wp_enqueue_script( 'CEU_newsmag-bootstrap', plugin_dir_path( __FILE__ )  . '/assets/vendors/bootstrap/bootstrap.min.js', array( 'jquery' ), false, true );

 /**
  * Load offscreen helper
  */
  /*
 wp_enqueue_script( 'newsmag-offscreen', plugin_dir_path( __FILE__ )  . '/assets/vendors/offscreen/offscreen.min.js', array( 'jquery' ), $newsmag['Version'], true );
  */
 wp_enqueue_script( 'CEU_newsmag-offscreen', plugin_dir_path( __FILE__ )  . '/assets/vendors/offscreen/offscreen.min.js', array( 'jquery' ), false , true );

 /**
  * Load the Sticky library
  */
  /*
 wp_enqueue_script( 'newsmag-sticky', plugin_dir_path( __FILE__ )  . '/assets/vendors/sticky/jquery.sticky.js', array( 'jquery' ), $newsmag['Version'], true );
  */
 wp_enqueue_script( 'CEU_newsmag-sticky', plugin_dir_path( __FILE__ )  . '/assets/vendors/sticky/jquery.sticky.js', array( 'jquery' ), false, true );

 /**
  * Theme styling
  */

 wp_enqueue_style( 'CEU_newsmag-style', get_stylesheet_uri() );
/*
wp_enqueue_style( 'newsmag-stylesheet', plugin_dir_path( __FILE__ )  . '/assets/css/style.css', array(), $newsmag['Version'] );
*/
        wp_enqueue_style( 'CEU_newsmag-stylesheet', plugin_dir_path( __FILE__ )  . '/assets/css/style.css', array(), false );

 /**
  * Load menu script & skip-link-focus-fix
  */

 wp_enqueue_script( 'CEU_newsmag-navigation', plugin_dir_path( __FILE__ )  . '/assets/js/navigation.js', array(), $newsmag['Version'], true );
/*  Added CEU_ prefix and also set version to default (false)
 wp_enqueue_script( 'newsmag-skip-link-focus-fix', plugin_dir_path( __FILE__ )  . '/assets/js/skip-link-focus-fix.js', array(), $newsmag['Version'], true );
*/
 wp_enqueue_script( 'CEU_newsmag-skip-link-focus-fix', plugin_dir_path( __FILE__ )  . '/assets/js/skip-link-focus-fix.js', array(), false, true );

 /**
  * Adsense loader
  */
/* Old version, updated version and CEU_ prefix
 wp_enqueue_script( 'newsmag-adsense-loader', plugin_dir_path( __FILE__ )  . '/assets/vendors/adsenseloader/jquery.adsenseloader.js', array('jquery'), $newsmag['Version'], true );
*/

 wp_enqueue_script( 'CEU_newsmag-adsense-loader', plugin_dir_path( __FILE__ )  . '/assets/vendors/adsenseloader/jquery.adsenseloader.js', array('jquery'), false, true );

 /**
  *Load the theme's core Javascript
  */

 wp_enqueue_script( 'CEU_machothemes-object', plugin_dir_path( __FILE__ )  . '/assets/vendors/machothemes/machothemes.min.js', array(), $newsmag['Version'], true );
 wp_enqueue_script( 'CEU_newsmag-functions', plugin_dir_path( __FILE__ )  . '/assets/js/functions.js', array('jquery'), $newsmag['Version'], true );
wp_localize_script( 'CEU_newsmag-functions', 'WPUrls', array(
  'siteurl' => get_option( 'siteurl' ),
  'theme'   => get_template_directory_uri(),
  'ajaxurl' => admin_url( 'admin-ajax.php' )
 ) );

 if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
  wp_enqueue_script( 'CEU_comment-reply' );
 }

 /**
  * OwlCarousel Library
  */
  /*
 wp_enqueue_script( 'owlCarousel-js', plugin_dir_path( __FILE__ )  . '/assets/vendors/owl-carousel/owl.carousel.min.js', array( 'jquery' ), $corrected_newsmag['Version'], true );
  */
    wp_enqueue_script( 'CEU_owlCarousel-js',
     plugin_dir_path( __FILE__ )  . '/assets/vendors/owl-carousel/owl.carousel.min.js', array( 'jquery' ), false, true );

    wp_enqueue_style( 'CEU_owlCarousel-main-css', plugin_dir_path( __FILE__ )  . '/assets/vendors/owl-carousel/owl.carousel.min.css' );

    wp_enqueue_style( 'CEU_owlCarousel-theme-css', plugin_dir_path( __FILE__ )  . '/assets/vendors/owl-carousel/owl.theme.default.css' );

}

add_action( 'wp_enqueue_scripts', 'corrected_newsmag_scripts' );

/**
 * Load admin fonts
 */
/*
function corrected_newsmag_admin_scripts() {
 $newsmag = wp_get_theme();
 wp_enqueue_style( 'newsmag-fonts', 'https://fonts.googleapis.com/css?family=Lato:100,300,400,700,900|Poppins:400,500,600,700', array(), $newsmag['Version'], 'all' );
}

add_action( 'admin_enqueue_scripts', 'corrected_newsmag_admin_scripts' );
*/

/**
 * Load editor styles
 */
/*
function corrected_newsmag_add_editor_styles() {
 add_editor_style( 'inc/assets/css/custom-editor-style.css' );
}

add_action( 'admin_init', 'corrected_newsmag_add_editor_styles' );
*/

Original Page with the Newsmag Pro Theme That Works (See: http://support.issues.owl.newyorkbusinessreview.com/ )

Image Showing Carousel Working With NewsMag Pro Theme (click link to view)

      VIEW ALL

        Books, Magazines, and Journals

       The Seven Secrets of Influence…

        April 24, 2017        0

        Books, Magazines, and Journals

       HBR Essentials and Two Complementary…

        April 23, 2017        0

        Books, Magazines, and Journals

       Harvard Business Review Magazine

        April 23, 2017        0

        Books, Magazines, and Journals

       HBR’s 10 Must Reads

        April 23, 2017        0

        Books, Magazines, and Journals

       Aiming at Amazon: The NEW…

        April 19, 2017        0

        Books, Magazines, and Journals

       Latest Business Books

        April 6, 2017        0

prev

next

Body:
The reasons it was not working were:
1)  The enqueue.php file did not properly load the content - plugin_dir_path( FILE ) was not correct.
2)  There was a conflict with the style sheets of the main theme and the style sheets of other themes.  Hence the CSS files needed to be updated.
3)  A custom token needed to be put at the beginning: CEU_newsmag-bootstrap for example.  That was in the existing code, but it was an earlier reason why the plugin did not work as intended.

Please submit questions to stephenelliott@newyorkbusinessreview.com

The plugin in the default Twenty-Seventeen Theme (with the additional WordPress plugin "amr shortcode any widget" used to place the widget on the page) can be seen at http://support.issues.owl.newyorkbusinessreview.com/ninja/test/

The corrected version of enqueue.php is below (with all the enqueue fixes):

<?php

/**
 * Enqueue scripts and styles in the frontend.
 */
function corrected_newsmag_scripts() {
 $corrected_newsmag = wp_get_theme();

 /**
  * Load Google Fonts
  */
  /*
 wp_enqueue_style( 'newsmag-fonts', '//fonts.googleapis.com/css?family=Lato:100,300,400,700,900|Poppins:400,500,600,700', array(), $newsmag['Version'], 'all' );
   */
 wp_enqueue_style( 'CEU_newsmag-fonts', '//fonts.googleapis.com/css?family=Lato:100,300,400,700,900|Poppins:400,500,600,700', array(), false, 'all' );

 wp_enqueue_style( 'CEU_font-awesome-style', plugin_dir_url( __FILE__ )  . '/assets/vendors/fontawesome//font-awesome.min.css' );

 /**
  * Load the bootstrap framework
  */
 wp_enqueue_style( 'CEU_bootstrap-style', plugin_dir_url( __FILE__ )  . '/assets/vendors/bootstrap/bootstrap.min.css' );
 wp_enqueue_style( 'CEU_bootstrap-theme-style', plugin_dir_url( __FILE__ )  . '/assets/vendors/bootstrap/bootstrap-theme.min.css' );
/*
 wp_enqueue_script( 'newsmag-bootstrap', plugin_dir_url( __FILE__ )  . '/assets/vendors/bootstrap/bootstrap.min.js', array( 'jquery' ), $newsmag['Version'], true );
*/
 wp_enqueue_script( 'CEU_newsmag-bootstrap', plugin_dir_url( __FILE__ )  . '/assets/vendors/bootstrap/bootstrap.min.js', array( 'jquery' ), false, true );

 /**
  * Load offscreen helper
  */
  /*
 wp_enqueue_script( 'newsmag-offscreen', plugin_dir_url( __FILE__ )  . '/assets/vendors/offscreen/offscreen.min.js', array( 'jquery' ), $newsmag['Version'], true );
  */
 wp_enqueue_script( 'CEU_newsmag-offscreen', plugin_dir_url( __FILE__ )  . '/assets/vendors/offscreen/offscreen.min.js', array( 'jquery' ), false , true );

 /**
  * Load the Sticky library
  */
  /*
 wp_enqueue_script( 'newsmag-sticky', plugin_dir_url( __FILE__ )  . '/assets/vendors/sticky/jquery.sticky.js', array( 'jquery' ), $newsmag['Version'], true );
  */
 wp_enqueue_script( 'CEU_newsmag-sticky', plugin_dir_url( __FILE__ )  . '/assets/vendors/sticky/jquery.sticky.js', array( 'jquery' ), false, true );

 /**
  * Theme styling
  */

 wp_enqueue_style( 'CEU_newsmag-style', get_stylesheet_uri() );
/*
wp_enqueue_style( 'newsmag-stylesheet', plugin_dir_url( __FILE__ )  . '/assets/css/style.css', array(), $newsmag['Version'] );
*/
        wp_enqueue_style( 'CEU_newsmag-stylesheet', plugin_dir_url( __FILE__ )  . '/assets/css/style.css', array(), false );

 /**
  * Load menu script & skip-link-focus-fix
  */

 wp_enqueue_script( 'CEU_newsmag-navigation', plugin_dir_url( __FILE__ )  . '/assets/js/navigation.js', array(), $newsmag['Version'], true );
/*  Added CEU_ prefix and also set version to default (false)
 wp_enqueue_script( 'newsmag-skip-link-focus-fix', plugin_dir_url( __FILE__ )  . '/assets/js/skip-link-focus-fix.js', array(), $newsmag['Version'], true );
*/
 wp_enqueue_script( 'CEU_newsmag-skip-link-focus-fix', plugin_dir_url( __FILE__ )  . '/assets/js/skip-link-focus-fix.js', array(), false, true );

 /**
  * Adsense loader
  */
/* Old version, updated version and CEU_ prefix
 wp_enqueue_script( 'newsmag-adsense-loader', plugin_dir_url( __FILE__ )  . '/assets/vendors/adsenseloader/jquery.adsenseloader.js', array('jquery'), $newsmag['Version'], true );
*/

 wp_enqueue_script( 'CEU_newsmag-adsense-loader', plugin_dir_url( __FILE__ )  . '/assets/vendors/adsenseloader/jquery.adsenseloader.js', array('jquery'), false, true );

 /**
  *Load the theme's core Javascript
  */

 wp_enqueue_script( 'CEU_machothemes-object', plugin_dir_url( __FILE__ )  . '/assets/vendors/machothemes/machothemes.min.js', array(), $newsmag['Version'], true );
 wp_enqueue_script( 'CEU_newsmag-functions', plugin_dir_url( __FILE__ )  . '/assets/js/functions.js', array('jquery'), $newsmag['Version'], true );
wp_localize_script( 'CEU_newsmag-functions', 'WPUrls', array(
  'siteurl' => get_option( 'siteurl' ),
  'theme'   => get_template_directory_uri(),
  'ajaxurl' => admin_url( 'admin-ajax.php' )
 ) );

 if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
  wp_enqueue_script( 'CEU_comment-reply' );
 }

 /**
  * OwlCarousel Library
  */
  /*
 wp_enqueue_script( 'owlCarousel-js', plugin_dir_url( __FILE__ )  . '/assets/vendors/owl-carousel/owl.carousel.min.js', array( 'jquery' ), $corrected_newsmag['Version'], true );
  */
    wp_enqueue_script( 'CEU_owlCarousel-js',
     plugin_dir_url( __FILE__ )  . '/assets/vendors/owl-carousel/owl.carousel.min.js', array( 'jquery' ), false, true );

    wp_enqueue_style( 'CEU_owlCarousel-main-css', plugin_dir_url( __FILE__ )  . '/assets/vendors/owl-carousel/owl.carousel.min.css' );

    wp_enqueue_style( 'CEU_owlCarousel-theme-css', plugin_dir_url( __FILE__ )  . '/assets/vendors/owl-carousel/owl.theme.default.css' );

}

add_action( 'wp_enqueue_scripts', 'corrected_newsmag_scripts' );

/**
 * Load admin fonts
 */
/*
function corrected_newsmag_admin_scripts() {
 $newsmag = wp_get_theme();
 wp_enqueue_style( 'newsmag-fonts', 'https://fonts.googleapis.com/css?family=Lato:100,300,400,700,900|Poppins:400,500,600,700', array(), $newsmag['Version'], 'all' );
}

add_action( 'admin_enqueue_scripts', 'corrected_newsmag_admin_scripts' );
*/

/**
 * Load editor styles
 */
/*
function corrected_newsmag_add_editor_styles() {
 add_editor_style( 'inc/assets/css/custom-editor-style.css' );
}

add_action( 'admin_init', 'corrected_newsmag_add_editor_styles' );
*/

The CSS files that needed modification (according to the developer we hired at Code Ninjas) were:

Files with changes: – assets/sass/elements/lists.scss –
  assets/sass/site/secondary/_widget-recent-posts.scss –
  assets/css/style.css

These can be found in the standard plugins directory on the demonstration website referenced earlier.  If there are questions feel free to email me at stephenelliott@newyorkbusinessreview.com (which is fast - as I receive an alert about your message - and also a little more flexible in including reference links an pictures currently) or else go to the contact page on http://www.newyorkbusinessreview.com and leave a message there on the contact form page - see the menu link on the bottom of the home page of the site.


问:
Android - OnClick inside gridview row
I'm trying to launch a activity from a button inside my gridview item, meaning that when user click on gridview Item it should do one function and when the user click on the button inside the gridview item it should do another function, let me elaborate, here is my single item layout that is being populated inside of my gridview;

```<code><android.support.v7.widget.CardView 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="wrap_content"
android:foreground="?android:attr/selectableItemBackground"
android:orientation="horizontal"
app:cardCornerRadius="5dp"
app:cardElevation="3dp"
app:cardPreventCornerOverlap="false"
app:cardUseCompatPadding="true">

<RelativeLayout
    android:id="@+id/single_row"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="10dp"
    android:paddingTop="10dp">

    <com.mikhaellopez.circularimageview.CircularImageView
        android:id="@+id/imgFood"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        app:civ_border_color="#ffffff"
        app:civ_border_width="2dp"
        app:civ_shadow="true"
        app:civ_shadow_color="#000000"
        app:civ_shadow_radius="10" />

<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_toRightOf="@+id/imgFood">

    <TextView
        android:id="@+id/txtName"
        android:layout_marginLeft="5dp"
        android:layout_marginStart="5dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Name"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textSize="16sp"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/currentid"
        android:layout_marginLeft="5dp"
        android:layout_marginStart="5dp"
        android:layout_below="@+id/txtName"
        android:text="Current ID : "
        android:visibility="visible"
        />

    <TextView
        android:id="@+id/studentid"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ID"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textSize="16sp"
        android:layout_below="@+id/txtName"
        android:layout_toRightOf="@+id/currentid"
        android:layout_marginEnd="30dp"
        android:layout_marginRight="30dp"
        />

    </RelativeLayout>

    <Button
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_gravity="end"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:id="@+id/editit"
        android:background="@android:drawable/btn_dialog"/>

</RelativeLayout>
</code>```

here is how the above layout looks:

and here is my adapter getview from where I try to do the intent/actions from;

```<code>@Override
public View getView(int position, View view, ViewGroup viewGroup) {

    View row = view;
    ViewHolder holder = new ViewHolder();

    if (row == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row = inflater.inflate(layout, null);

        holder.txtName = (TextView) row.findViewById(R.id.txtName);
        holder.txtPrice = (TextView) row.findViewById(R.id.studentid);
        holder.imageView = (CircularImageView) row.findViewById(R.id.imgFood);
        holder.dit = (Button) row.findViewById(R.id.editit);

        final ViewHolder finalHolder = holder;
        holder.dit.setOnClickListener(new View.OnClickListener() {

            String getname = finalHolder.txtName.getText().toString();
            String gethandicap = finalHolder.txtPrice.getText().toString();

            @Override
            public void onClick(View v) {
                // Do something
                Intent editintent = new Intent(context, MainActivity.class);
                editintent.putExtra("studentname", getname);
                editintent.putExtra("studentid", getID);
                context.startActivity(editintent);
            }
        });

        row.setTag(holder);
    } else {
        holder = (ViewHolder) row.getTag();
    }

    Sudentdb student = studentsList.get(position);

    holder.txtName.setText(student.getName());
    holder.txtPrice.setText(student.getID());

    if (student.getImage() != null && student.getImage().length > 0) {
        Glide.with(context)
                .load(student.getImage())
                .into(holder.imageView);
    } else {
        holder.imageView.setImageBitmap(null);
    }

    return row;

}
</code>```

The problem I'm having is that the button inside the gridview item is not performing any actions, in log it only says ACTION_DOWN and since I added a button inside the item the item onclick also doesn't work.

EDIT; ADDING GRIDVIEW ONCLICK AND LAYOUT

```<code>gridView = (GridView) findViewById(R.id.gridView);
    list = new ArrayList<>();
    adapter = new StudentListAdapter(this, R.layout.food_items, list);
    gridView.setAdapter(adapter);

    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {

            String dataFromGrid;
            dataFromGrid = ((TextView)(view.findViewById(R.id.txtName))).getText().toString();

            Intent i = new Intent(getApplicationContext(), Student.class);

            i.putExtra("unfromstudent",dataFromGrid);
            startActivity(i);
</code>```

gridview layout (I have tried focusable and clickable)

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clickable="true"
    android:focusable="true"
     >

    <GridView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:clickable="true"
        android:focusable="true"
        android:id="@+id/gridView"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:columnWidth="120dp"
        android:gravity="center"
        android:layout_margin="2dp"
        android:numColumns="1"

        />

</RelativeLayout>
</code>```

答:
Change you XML, i have tested below xml its works fine with
  GridView

```<code><android.support.v7.widget.CardView 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="wrap_content"
    android:foreground="?android:attr/selectableItemBackground"
    android:orientation="horizontal"
    app:cardCornerRadius="5dp"
    app:cardElevation="3dp"
    app:cardPreventCornerOverlap="false"
    app:cardUseCompatPadding="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:focusable="false"
        android:orientation="horizontal">

        <com.mikhaellopez.circularimageview.CircularImageView
            android:id="@+id/imgFood"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_margin="10dp"
            app:civ_border_color="#ffffff"
            app:civ_border_width="2dp"
            app:civ_shadow="true"
            app:civ_shadow_color="#000000"
            app:civ_shadow_radius="10" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal|center_vertical"
            android:layout_weight="1"
            android:gravity="center_horizontal|center_vertical"
            android:orientation="vertical">

            <TextView
                android:id="@+id/txtName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:layout_marginStart="5dp"
                android:text="Name"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:textSize="16sp" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <TextView
                    android:id="@+id/currentid"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/txtName"
                    android:layout_marginLeft="5dp"
                    android:layout_marginStart="5dp"
                    android:text="Current ID : "
                    android:visibility="visible" />

                <TextView
                    android:id="@+id/studentid"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/txtName"
                    android:layout_marginEnd="30dp"
                    android:layout_marginRight="30dp"
                    android:layout_toRightOf="@+id/currentid"
                    android:text="ID"
                    android:textAppearance="?android:attr/textAppearanceLarge"
                    android:textSize="16sp" />
            </LinearLayout>
        </LinearLayout>

        <LinearLayout
            android:layout_width="30dp"
            android:layout_height="30dp">

            <Button
                android:id="@+id/editit"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_gravity="end"
                android:background="@android:drawable/btn_dialog"
                android:focusable="false" />

        </LinearLayout>

    </LinearLayout>

</android.support.v7.widget.CardView>
</code>```

Your Grid View XML will be Like this.

```<code><GridView
        android:id="@+id/grid"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:focusable="true">

    </GridView>
</code>```

Title: Android - OnClick inside gridview row

Body:
I'm trying to launch a activity from a button inside my gridview item, meaning that when user click on gridview Item it should do one function and when the user click on the button inside the gridview item it should do another function, let me elaborate, here is my single item layout that is being populated inside of my gridview;

<android.support.v7.widget.CardView 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="wrap_content"
android:foreground="?android:attr/selectableItemBackground"
android:orientation="horizontal"
app:cardCornerRadius="5dp"
app:cardElevation="3dp"
app:cardPreventCornerOverlap="false"
app:cardUseCompatPadding="true">

<RelativeLayout
    android:id="@+id/single_row"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="10dp"
    android:paddingTop="10dp">

    <com.mikhaellopez.circularimageview.CircularImageView
        android:id="@+id/imgFood"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        app:civ_border_color="#ffffff"
        app:civ_border_width="2dp"
        app:civ_shadow="true"
        app:civ_shadow_color="#000000"
        app:civ_shadow_radius="10" />

<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_toRightOf="@+id/imgFood">

    <TextView
        android:id="@+id/txtName"
        android:layout_marginLeft="5dp"
        android:layout_marginStart="5dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Name"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textSize="16sp"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/currentid"
        android:layout_marginLeft="5dp"
        android:layout_marginStart="5dp"
        android:layout_below="@+id/txtName"
        android:text="Current ID : "
        android:visibility="visible"
        />

    <TextView
        android:id="@+id/studentid"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ID"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textSize="16sp"
        android:layout_below="@+id/txtName"
        android:layout_toRightOf="@+id/currentid"
        android:layout_marginEnd="30dp"
        android:layout_marginRight="30dp"
        />

    </RelativeLayout>

    <Button
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_gravity="end"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:id="@+id/editit"
        android:background="@android:drawable/btn_dialog"/>

</RelativeLayout>

here is how the above layout looks:

and here is my adapter getview from where I try to do the intent/actions from;

@Override
public View getView(int position, View view, ViewGroup viewGroup) {

    View row = view;
    ViewHolder holder = new ViewHolder();

    if (row == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row = inflater.inflate(layout, null);

        holder.txtName = (TextView) row.findViewById(R.id.txtName);
        holder.txtPrice = (TextView) row.findViewById(R.id.studentid);
        holder.imageView = (CircularImageView) row.findViewById(R.id.imgFood);
        holder.dit = (Button) row.findViewById(R.id.editit);

        final ViewHolder finalHolder = holder;
        holder.dit.setOnClickListener(new View.OnClickListener() {

            String getname = finalHolder.txtName.getText().toString();
            String gethandicap = finalHolder.txtPrice.getText().toString();

            @Override
            public void onClick(View v) {
                // Do something
                Intent editintent = new Intent(context, MainActivity.class);
                editintent.putExtra("studentname", getname);
                editintent.putExtra("studentid", getID);
                context.startActivity(editintent);
            }
        });

        row.setTag(holder);
    } else {
        holder = (ViewHolder) row.getTag();
    }

    Sudentdb student = studentsList.get(position);

    holder.txtName.setText(student.getName());
    holder.txtPrice.setText(student.getID());

    if (student.getImage() != null && student.getImage().length > 0) {
        Glide.with(context)
                .load(student.getImage())
                .into(holder.imageView);
    } else {
        holder.imageView.setImageBitmap(null);
    }

    return row;

}

The problem I'm having is that the button inside the gridview item is not performing any actions, in log it only says ACTION_DOWN and since I added a button inside the item the item onclick also doesn't work.

EDIT; ADDING GRIDVIEW ONCLICK AND LAYOUT

gridView = (GridView) findViewById(R.id.gridView);
    list = new ArrayList<>();
    adapter = new StudentListAdapter(this, R.layout.food_items, list);
    gridView.setAdapter(adapter);

    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {

            String dataFromGrid;
            dataFromGrid = ((TextView)(view.findViewById(R.id.txtName))).getText().toString();

            Intent i = new Intent(getApplicationContext(), Student.class);

            i.putExtra("unfromstudent",dataFromGrid);
            startActivity(i);

gridview layout (I have tried focusable and clickable)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clickable="true"
    android:focusable="true"
     >

    <GridView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:clickable="true"
        android:focusable="true"
        android:id="@+id/gridView"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:columnWidth="120dp"
        android:gravity="center"
        android:layout_margin="2dp"
        android:numColumns="1"

        />

</RelativeLayout>

Body:
Change you XML, i have tested below xml its works fine with
  GridView

<android.support.v7.widget.CardView 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="wrap_content"
    android:foreground="?android:attr/selectableItemBackground"
    android:orientation="horizontal"
    app:cardCornerRadius="5dp"
    app:cardElevation="3dp"
    app:cardPreventCornerOverlap="false"
    app:cardUseCompatPadding="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:focusable="false"
        android:orientation="horizontal">

        <com.mikhaellopez.circularimageview.CircularImageView
            android:id="@+id/imgFood"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_margin="10dp"
            app:civ_border_color="#ffffff"
            app:civ_border_width="2dp"
            app:civ_shadow="true"
            app:civ_shadow_color="#000000"
            app:civ_shadow_radius="10" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal|center_vertical"
            android:layout_weight="1"
            android:gravity="center_horizontal|center_vertical"
            android:orientation="vertical">

            <TextView
                android:id="@+id/txtName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:layout_marginStart="5dp"
                android:text="Name"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:textSize="16sp" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <TextView
                    android:id="@+id/currentid"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/txtName"
                    android:layout_marginLeft="5dp"
                    android:layout_marginStart="5dp"
                    android:text="Current ID : "
                    android:visibility="visible" />

                <TextView
                    android:id="@+id/studentid"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/txtName"
                    android:layout_marginEnd="30dp"
                    android:layout_marginRight="30dp"
                    android:layout_toRightOf="@+id/currentid"
                    android:text="ID"
                    android:textAppearance="?android:attr/textAppearanceLarge"
                    android:textSize="16sp" />
            </LinearLayout>
        </LinearLayout>

        <LinearLayout
            android:layout_width="30dp"
            android:layout_height="30dp">

            <Button
                android:id="@+id/editit"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_gravity="end"
                android:background="@android:drawable/btn_dialog"
                android:focusable="false" />

        </LinearLayout>

    </LinearLayout>

</android.support.v7.widget.CardView>

Your Grid View XML will be Like this.

<GridView
        android:id="@+id/grid"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:focusable="true">

    </GridView>


问:
How is a random number generated at runtime?
Since computers cannot pick random numbers(can they?) how is this random number actually generated. For example in C# we say,

```<code>Random.Next()
</code>```

What happens inside?

答:
I don't know much details but what I know is that a seed is used in order to generate the random numbers it is then based on some algorithm that uses that seed that a new number is obtained.

If you get random numbers based on the same seed they will be the same often.

ContentLicense: CC BY-SA 2.5

Body:
Since computers cannot pick random numbers(can they?) how is this random number actually generated. For example in C# we say,

Random.Next()

What happens inside?


问:
client side validation in htmlhelper without Model Class
I visited through different links but couldn't find desired answer. I am not using model for this view. Before sending data to server I want to check whether the text input is null or not.How can I validate it?</p>

```<code>@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="container">
    <h2>Student Information</h2>
    @using (Html.BeginForm("insert", "Menu", FormMethod.Post, new { id="target"}))
    {
        <label>First Name:</label>
        <input type="text" class="form-control" name="firstname" id="f_name" />
        <button type="submit" class="btn btn-success" >Insert</button>
    }
</div>

<script>
    $(function () {
        $("#target".submit(function (event) {
            event.preventDefault();
            //return false;
        })
    })
</script>
</code>```

答:
Try this, I use empty string ('') instead of null since usually empty textbox are just empty string and not necessarily null.</p>

```<code><script>
$(function () {
    $('button.btn').unbind();
    $('button.btn').click(function () {

        if($("#f_name").val() == ''){
            return false;
        }
        return true;
    })
})
</script>
</code>```

Body:
I visited through different links but couldn't find desired answer. I am not using model for this view. Before sending data to server I want to check whether the text input is null or not.How can I validate it?

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Student Information

    @using (Html.BeginForm("insert", "Menu", FormMethod.Post, new { id="target"}))
    {
        First Name:
        <input type="text" class="form-control" name="firstname" id="f_name" />
        <button type="submit" class="btn btn-success" >Insert</button>
    }

Body:
Try this, I use empty string ('') instead of null since usually empty textbox are just empty string and not necessarily null.

<script>
$(function () {
    $('button.btn').unbind();
    $('button.btn').click(function () {

        if($("#f_name").val() == ''){
            return false;
        }
        return true;
    })
})
</script>


问:
iOS Autolayout | View's height anchor
I'm using UITableViewAutomaticDimension to calculate cells height.
In my custom cell, height depends on it's content (text).
So i need to layout UIImageView height. I need to set UIImageView maximum height to some constant. But when text is short UIImageView's height becomes smaller to fit its superview with inset.

Current result

Needs to be

Playground code example:

```<code>//: Playground - noun: a place where people can play

import UIKit
import PlaygroundSupport

class ViewController: UIViewController {

    let descriptions = ["", "Curabitur.", "Senectus sit consectetur fermentum nisi suspendisse a condimentum at vestibulum a vestibulum a nostra fermentum molestie sodales molestie id viverra scelerisque consectetur.Penatibus a dictum metus mus commodo a hac morbi parturient parturient convallis ultrices a mi id.Fringilla lobortis suspendisse vestibulum quisque consectetur imperdiet.", "Condimentum adipiscing.", "Cras scelerisque parturient vitae class sollicitudin.", "Integer adipiscing a adipiscing parturient tempus condimentum a interdum facilisis feugiat.", "Donec eros eleifend a ullamcorper class scelerisque nisi nullam nisi sociis ante iaculis pharetra malesuada nibh sit consectetur condimentum.Nibh sollicitudin."]

    lazy var tableView: UITableView = {
        let tv = UITableView()
        tv.dataSource = self
        tv.estimatedRowHeight = 80
        tv.rowHeight = UITableViewAutomaticDimension
        tv.separatorStyle = .none
        tv.register(PrototypeCell.self, forCellReuseIdentifier: NSStringFromClass(PrototypeCell.self))
        return tv
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.frame = CGRect(x: 0, y: 0, width: 320, height: 480)
        tableView.frame = view.frame
        view.addSubview(self.tableView)
    }
}

extension ViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return descriptions.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(PrototypeCell.self), for: indexPath) as! PrototypeCell
        cell.titleLabel.text = "Title #\(indexPath.row)"
        cell.subtitleLabel.text = "Subtitle #\(indexPath.row)"
        cell.descriptionLabel.text = descriptions[indexPath.row]
        return cell
    }
}

class PrototypeCell: UITableViewCell {

    let foregroundView: UIView = {
        let v = UIView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .red
        return v
    }()

    let detailImageView: UIImageView = {
        let iv = UIImageView()
        iv.translatesAutoresizingMaskIntoConstraints = false
        iv.backgroundColor = .gray
        return iv
    }()

    let titleLabel: UILabel = {
        let lbl = UILabel()
        lbl.translatesAutoresizingMaskIntoConstraints = false
        lbl.numberOfLines = 1
        lbl.text = "Title"
        return lbl
    }()

    let subtitleLabel: UILabel = {
        let lbl = UILabel()
        lbl.translatesAutoresizingMaskIntoConstraints = false
        lbl.numberOfLines = 1
        lbl.text = "Subtitile"
        lbl.font = UIFont.systemFont(ofSize: 12)
        return lbl
    }()

    let descriptionLabel: UILabel = {
        let lbl = UILabel()
        lbl.translatesAutoresizingMaskIntoConstraints = false
        lbl.numberOfLines = 0
        lbl.font = UIFont.systemFont(ofSize: 10)
        return lbl
    }()

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none

        contentView.addSubview(foregroundView)
        foregroundView.addSubview(detailImageView)
        foregroundView.addSubview(titleLabel)
        foregroundView.addSubview(subtitleLabel)
        foregroundView.addSubview(descriptionLabel)

        NSLayoutConstraint.activate([
                foregroundView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 4),
                foregroundView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -4),
                foregroundView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -4),
                foregroundView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 4),

                detailImageView.heightAnchor.constraint(equalToConstant: 64),
                detailImageView.widthAnchor.constraint(equalToConstant: 64),
                detailImageView.topAnchor.constraint(equalTo: foregroundView.topAnchor, constant: 4),
                detailImageView.leadingAnchor.constraint(equalTo: foregroundView.leadingAnchor, constant: 4),

                titleLabel.topAnchor.constraint(equalTo: foregroundView.topAnchor, constant: 4),
                titleLabel.trailingAnchor.constraint(equalTo: foregroundView.trailingAnchor, constant: 4),
                titleLabel.leadingAnchor.constraint(equalTo: detailImageView.trailingAnchor, constant: 4),

                subtitleLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 2),
                subtitleLabel.trailingAnchor.constraint(equalTo: foregroundView.trailingAnchor, constant: -4),
                subtitleLabel.leadingAnchor.constraint(equalTo: detailImageView.trailingAnchor, constant: 4),

                descriptionLabel.topAnchor.constraint(equalTo: subtitleLabel.bottomAnchor, constant: 2),
                descriptionLabel.trailingAnchor.constraint(equalTo: foregroundView.trailingAnchor, constant: -4),
                descriptionLabel.bottomAnchor.constraint(equalTo: foregroundView.bottomAnchor, constant: -4),
                descriptionLabel.leadingAnchor.constraint(equalTo: detailImageView.trailingAnchor, constant: 4),
            ])
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

var ctrl = ViewController()
PlaygroundPage.current.liveView = ctrl.view
</code>```

Thanks everyone!

Final solution:

```<code>    //: Playground - noun: a place where people can play

import UIKit
import PlaygroundSupport

class ViewController: UIViewController {

    let descriptions = [nil, "Curabitur.", "Senectus sit consectetur fermentum nisi suspendisse a condimentum at vestibulum a vestibulum a nostra fermentum molestie sodales molestie id viverra scelerisque consectetur.Penatibus a dictum metus mus commodo a hac morbi parturient parturient convallis ultrices a mi id.Fringilla lobortis suspendisse vestibulum quisque consectetur imperdiet.", "Condimentum adipiscing.", "Cras scelerisque parturient vitae class sollicitudin.", "Integer adipiscing a adipiscing parturient tempus condimentum a interdum facilisis feugiat.", "Donec eros eleifend a ullamcorper class scelerisque nisi nullam nisi sociis ante iaculis pharetra malesuada nibh sit consectetur condimentum.Nibh sollicitudin."]

    lazy var tableView: UITableView = {
        let tv = UITableView()
        tv.dataSource = self
        tv.estimatedRowHeight = 80
        tv.rowHeight = UITableViewAutomaticDimension
        tv.separatorStyle = .none
        tv.register(PrototypeCell.self, forCellReuseIdentifier: NSStringFromClass(PrototypeCell.self))
        return tv
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.frame = CGRect(x: 0, y: 0, width: 320, height: 480)
        tableView.frame = view.frame
        view.addSubview(self.tableView)
    }
}

extension ViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return descriptions.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(PrototypeCell.self), for: indexPath) as! PrototypeCell
        cell.titleLabel.text = "Title #\(indexPath.row)"
        cell.subtitleLabel.text = "Subtitle #\(indexPath.row)"
        cell.descriptionLabel.text = descriptions[indexPath.row]
        return cell
    }
}

class PrototypeCell: UITableViewCell {

    let foregroundView: UIView = {
        let v = UIView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .red
        return v
    }()

    let detailImageView: UIImageView = {
        let iv = UIImageView()
        iv.translatesAutoresizingMaskIntoConstraints = false
        iv.backgroundColor = .gray
        return iv
    }()

    let titleLabel: UILabel = {
        let lbl = UILabel()
        lbl.translatesAutoresizingMaskIntoConstraints = false
        lbl.numberOfLines = 1
        lbl.text = "Title"
        return lbl
    }()

    let subtitleLabel: UILabel = {
        let lbl = UILabel()
        lbl.translatesAutoresizingMaskIntoConstraints = false
        lbl.numberOfLines = 1
        lbl.text = "Subtitile"
        lbl.font = UIFont.systemFont(ofSize: 12)
        return lbl
    }()

    let descriptionLabel: UILabel = {
        let lbl = UILabel()
        lbl.translatesAutoresizingMaskIntoConstraints = false
        lbl.numberOfLines = 0
        lbl.font = UIFont.systemFont(ofSize: 10)
        return lbl
    }()

    var detailImageViewBottomAnchor: NSLayoutConstraint!

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        detailImageViewBottomAnchor = detailImageView.bottomAnchor.constraint(equalTo: foregroundView.bottomAnchor, constant: -4)
        detailImageViewBottomAnchor.priority = 749
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none

        contentView.addSubview(foregroundView)
        foregroundView.addSubview(detailImageView)
        foregroundView.addSubview(titleLabel)
        foregroundView.addSubview(subtitleLabel)
        foregroundView.addSubview(descriptionLabel)

        NSLayoutConstraint.activate([
                foregroundView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 4),
                foregroundView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -4),
                foregroundView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -4),
                foregroundView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 4),

                detailImageView.heightAnchor.constraint(lessThanOrEqualToConstant: 64),
                detailImageView.widthAnchor.constraint(equalToConstant: 64),
                detailImageView.topAnchor.constraint(equalTo: foregroundView.topAnchor, constant: 4),
                detailImageViewBottomAnchor,
                detailImageView.leadingAnchor.constraint(equalTo: foregroundView.leadingAnchor, constant: 4),

                titleLabel.topAnchor.constraint(equalTo: foregroundView.topAnchor, constant: 4),
                titleLabel.trailingAnchor.constraint(equalTo: foregroundView.trailingAnchor, constant: 4),
                titleLabel.leadingAnchor.constraint(equalTo: detailImageView.trailingAnchor, constant: 4),

                subtitleLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 2),
                subtitleLabel.trailingAnchor.constraint(equalTo: foregroundView.trailingAnchor, constant: -4),
                subtitleLabel.leadingAnchor.constraint(equalTo: detailImageView.trailingAnchor, constant: 4),

                descriptionLabel.topAnchor.constraint(equalTo: subtitleLabel.bottomAnchor, constant: 2),
                descriptionLabel.trailingAnchor.constraint(equalTo: foregroundView.trailingAnchor, constant: -4),
                descriptionLabel.bottomAnchor.constraint(equalTo: foregroundView.bottomAnchor, constant: -4),
                descriptionLabel.leadingAnchor.constraint(equalTo: detailImageView.trailingAnchor, constant: 4),

            ])
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

var ctrl = ViewController()
PlaygroundPage.current.liveView = ctrl.view
</code>```

答:
In your PrototypeCell's layoutSubviews()  function add

```<code>  if self.view.frame.size.height < 68 {
        detailImageView.heightAnchor.constraint(equalToConstant: self.frame.size.height - 8)
    } else {
    detailImageView.heightAnchor.constraint(equalToConstant: 64)
   }
</code>```

Here if the cell height is less than 68 then the imageview height will be the cell height - 8. Where 8 being top space of imageview(4) + the bottom space of imageview(4).

Title: iOS Autolayout | View's height anchor

Body:
I'm using UITableViewAutomaticDimension to calculate cells height.
In my custom cell, height depends on it's content (text).
So i need to layout UIImageView height. I need to set UIImageView maximum height to some constant. But when text is short UIImageView's height becomes smaller to fit its superview with inset.

Current result

Needs to be

Playground code example:

//: Playground - noun: a place where people can play

import UIKit
import PlaygroundSupport

class ViewController: UIViewController {

    let descriptions = ["", "Curabitur.", "Senectus sit consectetur fermentum nisi suspendisse a condimentum at vestibulum a vestibulum a nostra fermentum molestie sodales molestie id viverra scelerisque consectetur.Penatibus a dictum metus mus commodo a hac morbi parturient parturient convallis ultrices a mi id.Fringilla lobortis suspendisse vestibulum quisque consectetur imperdiet.", "Condimentum adipiscing.", "Cras scelerisque parturient vitae class sollicitudin.", "Integer adipiscing a adipiscing parturient tempus condimentum a interdum facilisis feugiat.", "Donec eros eleifend a ullamcorper class scelerisque nisi nullam nisi sociis ante iaculis pharetra malesuada nibh sit consectetur condimentum.Nibh sollicitudin."]

    lazy var tableView: UITableView = {
        let tv = UITableView()
        tv.dataSource = self
        tv.estimatedRowHeight = 80
        tv.rowHeight = UITableViewAutomaticDimension
        tv.separatorStyle = .none
        tv.register(PrototypeCell.self, forCellReuseIdentifier: NSStringFromClass(PrototypeCell.self))
        return tv
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.frame = CGRect(x: 0, y: 0, width: 320, height: 480)
        tableView.frame = view.frame
        view.addSubview(self.tableView)
    }
}

extension ViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return descriptions.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(PrototypeCell.self), for: indexPath) as! PrototypeCell
        cell.titleLabel.text = "Title #\(indexPath.row)"
        cell.subtitleLabel.text = "Subtitle #\(indexPath.row)"
        cell.descriptionLabel.text = descriptions[indexPath.row]
        return cell
    }
}

class PrototypeCell: UITableViewCell {

    let foregroundView: UIView = {
        let v = UIView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .red
        return v
    }()

    let detailImageView: UIImageView = {
        let iv = UIImageView()
        iv.translatesAutoresizingMaskIntoConstraints = false
        iv.backgroundColor = .gray
        return iv
    }()

    let titleLabel: UILabel = {
        let lbl = UILabel()
        lbl.translatesAutoresizingMaskIntoConstraints = false
        lbl.numberOfLines = 1
        lbl.text = "Title"
        return lbl
    }()

    let subtitleLabel: UILabel = {
        let lbl = UILabel()
        lbl.translatesAutoresizingMaskIntoConstraints = false
        lbl.numberOfLines = 1
        lbl.text = "Subtitile"
        lbl.font = UIFont.systemFont(ofSize: 12)
        return lbl
    }()

    let descriptionLabel: UILabel = {
        let lbl = UILabel()
        lbl.translatesAutoresizingMaskIntoConstraints = false
        lbl.numberOfLines = 0
        lbl.font = UIFont.systemFont(ofSize: 10)
        return lbl
    }()

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none

        contentView.addSubview(foregroundView)
        foregroundView.addSubview(detailImageView)
        foregroundView.addSubview(titleLabel)
        foregroundView.addSubview(subtitleLabel)
        foregroundView.addSubview(descriptionLabel)

        NSLayoutConstraint.activate([
                foregroundView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 4),
                foregroundView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -4),
                foregroundView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -4),
                foregroundView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 4),

                detailImageView.heightAnchor.constraint(equalToConstant: 64),
                detailImageView.widthAnchor.constraint(equalToConstant: 64),
                detailImageView.topAnchor.constraint(equalTo: foregroundView.topAnchor, constant: 4),
                detailImageView.leadingAnchor.constraint(equalTo: foregroundView.leadingAnchor, constant: 4),

                titleLabel.topAnchor.constraint(equalTo: foregroundView.topAnchor, constant: 4),
                titleLabel.trailingAnchor.constraint(equalTo: foregroundView.trailingAnchor, constant: 4),
                titleLabel.leadingAnchor.constraint(equalTo: detailImageView.trailingAnchor, constant: 4),

                subtitleLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 2),
                subtitleLabel.trailingAnchor.constraint(equalTo: foregroundView.trailingAnchor, constant: -4),
                subtitleLabel.leadingAnchor.constraint(equalTo: detailImageView.trailingAnchor, constant: 4),

                descriptionLabel.topAnchor.constraint(equalTo: subtitleLabel.bottomAnchor, constant: 2),
                descriptionLabel.trailingAnchor.constraint(equalTo: foregroundView.trailingAnchor, constant: -4),
                descriptionLabel.bottomAnchor.constraint(equalTo: foregroundView.bottomAnchor, constant: -4),
                descriptionLabel.leadingAnchor.constraint(equalTo: detailImageView.trailingAnchor, constant: 4),
            ])
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

var ctrl = ViewController()
PlaygroundPage.current.liveView = ctrl.view

Thanks everyone!

Final solution:

    //: Playground - noun: a place where people can play

import UIKit
import PlaygroundSupport

class ViewController: UIViewController {

    let descriptions = [nil, "Curabitur.", "Senectus sit consectetur fermentum nisi suspendisse a condimentum at vestibulum a vestibulum a nostra fermentum molestie sodales molestie id viverra scelerisque consectetur.Penatibus a dictum metus mus commodo a hac morbi parturient parturient convallis ultrices a mi id.Fringilla lobortis suspendisse vestibulum quisque consectetur imperdiet.", "Condimentum adipiscing.", "Cras scelerisque parturient vitae class sollicitudin.", "Integer adipiscing a adipiscing parturient tempus condimentum a interdum facilisis feugiat.", "Donec eros eleifend a ullamcorper class scelerisque nisi nullam nisi sociis ante iaculis pharetra malesuada nibh sit consectetur condimentum.Nibh sollicitudin."]

    lazy var tableView: UITableView = {
        let tv = UITableView()
        tv.dataSource = self
        tv.estimatedRowHeight = 80
        tv.rowHeight = UITableViewAutomaticDimension
        tv.separatorStyle = .none
        tv.register(PrototypeCell.self, forCellReuseIdentifier: NSStringFromClass(PrototypeCell.self))
        return tv
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.frame = CGRect(x: 0, y: 0, width: 320, height: 480)
        tableView.frame = view.frame
        view.addSubview(self.tableView)
    }
}

extension ViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return descriptions.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(PrototypeCell.self), for: indexPath) as! PrototypeCell
        cell.titleLabel.text = "Title #\(indexPath.row)"
        cell.subtitleLabel.text = "Subtitle #\(indexPath.row)"
        cell.descriptionLabel.text = descriptions[indexPath.row]
        return cell
    }
}

class PrototypeCell: UITableViewCell {

    let foregroundView: UIView = {
        let v = UIView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .red
        return v
    }()

    let detailImageView: UIImageView = {
        let iv = UIImageView()
        iv.translatesAutoresizingMaskIntoConstraints = false
        iv.backgroundColor = .gray
        return iv
    }()

    let titleLabel: UILabel = {
        let lbl = UILabel()
        lbl.translatesAutoresizingMaskIntoConstraints = false
        lbl.numberOfLines = 1
        lbl.text = "Title"
        return lbl
    }()

    let subtitleLabel: UILabel = {
        let lbl = UILabel()
        lbl.translatesAutoresizingMaskIntoConstraints = false
        lbl.numberOfLines = 1
        lbl.text = "Subtitile"
        lbl.font = UIFont.systemFont(ofSize: 12)
        return lbl
    }()

    let descriptionLabel: UILabel = {
        let lbl = UILabel()
        lbl.translatesAutoresizingMaskIntoConstraints = false
        lbl.numberOfLines = 0
        lbl.font = UIFont.systemFont(ofSize: 10)
        return lbl
    }()

    var detailImageViewBottomAnchor: NSLayoutConstraint!

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        detailImageViewBottomAnchor = detailImageView.bottomAnchor.constraint(equalTo: foregroundView.bottomAnchor, constant: -4)
        detailImageViewBottomAnchor.priority = 749
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none

        contentView.addSubview(foregroundView)
        foregroundView.addSubview(detailImageView)
        foregroundView.addSubview(titleLabel)
        foregroundView.addSubview(subtitleLabel)
        foregroundView.addSubview(descriptionLabel)

        NSLayoutConstraint.activate([
                foregroundView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 4),
                foregroundView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -4),
                foregroundView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -4),
                foregroundView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 4),

                detailImageView.heightAnchor.constraint(lessThanOrEqualToConstant: 64),
                detailImageView.widthAnchor.constraint(equalToConstant: 64),
                detailImageView.topAnchor.constraint(equalTo: foregroundView.topAnchor, constant: 4),
                detailImageViewBottomAnchor,
                detailImageView.leadingAnchor.constraint(equalTo: foregroundView.leadingAnchor, constant: 4),

                titleLabel.topAnchor.constraint(equalTo: foregroundView.topAnchor, constant: 4),
                titleLabel.trailingAnchor.constraint(equalTo: foregroundView.trailingAnchor, constant: 4),
                titleLabel.leadingAnchor.constraint(equalTo: detailImageView.trailingAnchor, constant: 4),

                subtitleLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 2),
                subtitleLabel.trailingAnchor.constraint(equalTo: foregroundView.trailingAnchor, constant: -4),
                subtitleLabel.leadingAnchor.constraint(equalTo: detailImageView.trailingAnchor, constant: 4),

                descriptionLabel.topAnchor.constraint(equalTo: subtitleLabel.bottomAnchor, constant: 2),
                descriptionLabel.trailingAnchor.constraint(equalTo: foregroundView.trailingAnchor, constant: -4),
                descriptionLabel.bottomAnchor.constraint(equalTo: foregroundView.bottomAnchor, constant: -4),
                descriptionLabel.leadingAnchor.constraint(equalTo: detailImageView.trailingAnchor, constant: 4),

            ])
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

var ctrl = ViewController()
PlaygroundPage.current.liveView = ctrl.view

Body:
In your PrototypeCell's layoutSubviews()  function add

  if self.view.frame.size.height < 68 {
        detailImageView.heightAnchor.constraint(equalToConstant: self.frame.size.height - 8)
    } else {
    detailImageView.heightAnchor.constraint(equalToConstant: 64)
   }

Here if the cell height is less than 68 then the imageview height will be the cell height - 8. Where 8 being top space of imageview(4) + the bottom space of imageview(4).


问:
How can I make node-inspector restart when node is restarted?
I use node-inspector a lot. When I edit my code and restart, I get the inevitable

Detached from the target

Error when a new process starts. I always have to go find the tab node inspector is on and restart it.

I was wondering if I could avoid this. For example, send a message to node-inspector from node to tell the browsers tab running node-inspector to restart.

答:
Cross-posting slightly from this SO, with an update to this topic.

There is a link in Chrome (58) standard Developer Pane which opens a new "headless" window which reconnects magically to node inspect no matter how the app is rebuilt / restarted.

I'm running Express.js e.g. DEBUG=myapp:* supervisor -- --inspect bin/www & and found it difficult to reconnect using the normal guid-laden URL which keeps changing. But this Chrome tool works all day reconnecting reliably.

Under Threads > Main, you should see "Node instance available. Connect".

I find the new-window less usable as I'd prefer a tab, but the auto-reconnect is so reliable I'll live with that!

The only downside I've found is when it does reconnect it clears all breakpoints.


问:
Hosting React/Redux Web Apps (front end)
One thing I do not quite understand yet is this. Say I have a website or single page app, made with React/Redux. Say I have no API calls or anything like this, so it's just the front-end I am talking about.

Do I have any restrictions when it comes to hosting?

People speak of Heroku & AWS here a lot, but as I understand it this concerns only the backend (?) Could I just host my React site with a 'traditional' provider or would I have to look out for something more specific?

答:
There are no specific requirements for hosting a react JS webapp.

Let's say you're using webpack to build your webapp, it'll build a static javascript file that need to be served just like regular static assets.

So just the way you'd serve any other website that has static html/css/js assets.

That is the case when you've no special requirements. Now if you wish to build on the server you'd expect the server to run nodejs and have decent memory to support the build process. If you need to do caching/load balancing/rate limiting you'll have to use different required solutions.