草庐IT

android - 如何在 Android 中创建幻灯片布局动画?

coder 2023-12-05 原文

您好,我想在“我的 Activity ”中创建幻灯片动画,如图片所示。 当我点击 More 按钮时,橙色布局应该像白色布局上的 slider 一样出现,当我点击 Less 按钮时,它应该像 slider 一样下降。

请向我推荐任何示例代码或任何教程,以获得创建此类方法的最佳方法。

谢谢!

最佳答案

使用此Panel 类 这将满足您的要求,您还可以处理该事件。

引用:http://code.google.com/p/android-misc-widgets/

面板.java

public class Panel extends LinearLayout {

    /**
     * Callback invoked when the panel is opened/closed.
     */
    public static interface OnPanelListener {
        /**
         * Invoked when the panel becomes fully closed.
         */
        public void onPanelClosed(Panel panel);
        /**
         * Invoked when the panel becomes fully opened.
         */
        public void onPanelOpened(Panel panel);
    }

    private boolean mIsShrinking;
    private int mPosition;
    private int mDuration;
    private boolean mLinearFlying;
    private int mHandleId;
    private int mContentId;
    private View mHandle;
    private View mContent;
    private Drawable mOpenedHandle;
    private Drawable mClosedHandle;
    private float mTrackX;
    private float mTrackY;
    private float mVelocity;

    private OnPanelListener panelListener;

    public static final int TOP = 0;
    public static final int BOTTOM = 1;
    public static final int LEFT = 2;
    public static final int RIGHT = 3;

    private enum State {
        ABOUT_TO_ANIMATE,
        ANIMATING,
        READY,
        TRACKING,
        FLYING,
    };
    private State mState;
    private Interpolator mInterpolator;
    private GestureDetector mGestureDetector;
    private int mContentHeight;
    private int mContentWidth;
    private int mOrientation;
    private float mWeight;
    private PanelOnGestureListener mGestureListener;
    private boolean mBringToFront;

    public Panel(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Panel);
        mDuration = a.getInteger(R.styleable.Panel_animationDuration, 750);     // duration defaults to 750 ms
        mPosition = a.getInteger(R.styleable.Panel_position, BOTTOM);           // position defaults to BOTTOM
        mLinearFlying = a.getBoolean(R.styleable.Panel_linearFlying, false);    // linearFlying defaults to false
        mWeight = a.getFraction(R.styleable.Panel_weight, 0, 1, 0.0f);          // weight defaults to 0.0
        if (mWeight < 0 || mWeight > 1) {
            mWeight = 0.0f;
            //Log.w(TAG, a.getPositionDescription() + ": weight must be > 0 and <= 1");
        }
        mOpenedHandle = a.getDrawable(R.styleable.Panel_openedHandle);
        mClosedHandle = a.getDrawable(R.styleable.Panel_closedHandle);

        RuntimeException e = null;
        mHandleId = a.getResourceId(R.styleable.Panel_handle, 0);
        if (mHandleId == 0) {
            e = new IllegalArgumentException(a.getPositionDescription() + 
                    ": The handle attribute is required and must refer to a valid child.");
        }
        mContentId = a.getResourceId(R.styleable.Panel_content, 0);
        if (mContentId == 0) {
            e = new IllegalArgumentException(a.getPositionDescription() + 
                    ": The content attribute is required and must refer to a valid child.");
        }
        a.recycle();

        if (e != null) {
            throw e;
        }
        mOrientation = (mPosition == TOP || mPosition == BOTTOM)? VERTICAL : HORIZONTAL;
        setOrientation(mOrientation);
        mState = State.READY;
        mGestureListener = new PanelOnGestureListener();
        mGestureDetector = new GestureDetector(mGestureListener);
        mGestureDetector.setIsLongpressEnabled(false);

        // i DON'T really know why i need this...
        setBaselineAligned(false);
    }

    /**
     * Sets the listener that receives a notification when the panel becomes open/close.
     *
     * @param onPanelListener The listener to be notified when the panel is opened/closed.
     */
    public void setOnPanelListener(OnPanelListener onPanelListener) {
        panelListener = onPanelListener;
    }

    /**
     * Gets Panel's mHandle
     * 
     * @return Panel's mHandle
     */
    public View getHandle() {
        return mHandle;
    }

    /**
     * Gets Panel's mContent
     * 
     * @return Panel's mContent 
     */
    public View getContent() {
        return mContent;
    }


    /**
     * Sets the acceleration curve for panel's animation.
     * 
     * @param i The interpolator which defines the acceleration curve 
     */
    public void setInterpolator(Interpolator i) {
        mInterpolator = i; 
    }

    /**
     * Set the opened state of Panel.
     * 
     * @param open True if Panel is to be opened, false if Panel is to be closed.
     * @param animate True if use animation, false otherwise.
     *
     * @return True if operation was performed, false otherwise.
     * 
     */
    public boolean setOpen(boolean open, boolean animate) {
        if (mState == State.READY && isOpen() ^ open) {
            mIsShrinking = !open;
            if (animate) {
                mState = State.ABOUT_TO_ANIMATE;
                if (!mIsShrinking) {
                    // this could make flicker so we test mState in dispatchDraw()
                    // to see if is equal to ABOUT_TO_ANIMATE
                    mContent.setVisibility(VISIBLE);
                }
                post(startAnimation);
            } else {
                mContent.setVisibility(open? VISIBLE : GONE);
                postProcess();
            }
            return true;
        }
        return false;
    }

    /**
     * Returns the opened status for Panel.
     * 
     * @return True if Panel is opened, false otherwise.
     */
    public boolean isOpen() {
        return mContent.getVisibility() == VISIBLE;
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        mHandle = findViewById(mHandleId);
        if (mHandle == null) {
            String name = getResources().getResourceEntryName(mHandleId);
            throw new RuntimeException("Your Panel must have a child View whose id attribute is 'R.id." + name + "'");
        }
        mHandle.setOnTouchListener(touchListener);
        mHandle.setOnClickListener(clickListener);

        mContent = findViewById(mContentId);
        if (mContent == null) {
            String name = getResources().getResourceEntryName(mHandleId);
            throw new RuntimeException("Your Panel must have a child View whose id attribute is 'R.id." + name + "'");
        }

        // reposition children
        removeView(mHandle);
        removeView(mContent);
        if (mPosition == TOP || mPosition == LEFT) {
            addView(mContent);
            addView(mHandle);
        } else {
            addView(mHandle);
            addView(mContent);
        }

        if (mClosedHandle != null) {
            mHandle.setBackgroundDrawable(mClosedHandle);
        }
        mContent.setClickable(true);
        mContent.setVisibility(GONE);
        if (mWeight > 0) {
            ViewGroup.LayoutParams params = mContent.getLayoutParams();
            if (mOrientation == VERTICAL) {
                params.height = ViewGroup.LayoutParams.FILL_PARENT;
            } else {
                params.width = ViewGroup.LayoutParams.FILL_PARENT;
            }
            mContent.setLayoutParams(params);
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        ViewParent parent = getParent();
        if (parent != null && parent instanceof FrameLayout) {
            mBringToFront = true;
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (mWeight > 0 && mContent.getVisibility() == VISIBLE) {
            View parent = (View) getParent();
            if (parent != null) {
                if (mOrientation == VERTICAL) {
                    heightMeasureSpec = MeasureSpec.makeMeasureSpec((int) (parent.getHeight() * mWeight), MeasureSpec.EXACTLY);
                } else {
                    widthMeasureSpec = MeasureSpec.makeMeasureSpec((int) (parent.getWidth() * mWeight), MeasureSpec.EXACTLY);
                }
            }
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        mContentWidth = mContent.getWidth();
        mContentHeight = mContent.getHeight();
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
//      String name = getResources().getResourceEntryName(getId());
//      //Log.d(TAG, name + " ispatchDraw " + mState);
        // this is why 'mState' was added:
        // avoid flicker before animation start
        if (mState == State.ABOUT_TO_ANIMATE && !mIsShrinking) {
            int delta = mOrientation == VERTICAL? mContentHeight : mContentWidth;
            if (mPosition == LEFT || mPosition == TOP) {
                delta = -delta;
            }
            if (mOrientation == VERTICAL) {
                canvas.translate(0, delta);
            } else {
                canvas.translate(delta, 0);
            }
        }
        if (mState == State.TRACKING || mState == State.FLYING) {
            canvas.translate(mTrackX, mTrackY);
        }
        super.dispatchDraw(canvas);
    }

    private float ensureRange(float v, int min, int max) {
        v = Math.max(v, min);
        v = Math.min(v, max);
        return v;
    }

    OnTouchListener touchListener = new OnTouchListener() {
        int initX;
        int initY;
        boolean setInitialPosition;
        public boolean onTouch(View v, MotionEvent event) {
            if (mState == State.ANIMATING) {
                // we are animating
                return false;
            }
//          //Log.d(TAG, "state: " + mState + " x: " + event.getX() + " y: " + event.getY());
            int action = event.getAction();
            if (action == MotionEvent.ACTION_DOWN) {
                if (mBringToFront) {
                    bringToFront();
                }
                initX = 0;
                initY = 0;
                if (mContent.getVisibility() == GONE) {
                    // since we may not know content dimensions we use factors here
                    if (mOrientation == VERTICAL) {
                        initY = mPosition == TOP? -1 : 1;
                    } else {
                        initX = mPosition == LEFT? -1 : 1;
                    }
                }
                setInitialPosition = true;
            } else {
                if (setInitialPosition) {
                    // now we know content dimensions, so we multiply factors...
                    initX *= mContentWidth;
                    initY *= mContentHeight;
                    // ... and set initial panel's position
                    mGestureListener.setScroll(initX, initY);
                    setInitialPosition = false;
                    // for offsetLocation we have to invert values
                    initX = -initX;
                    initY = -initY;
                }
                // offset every ACTION_MOVE & ACTION_UP event 
                event.offsetLocation(initX, initY);
            }
            if (!mGestureDetector.onTouchEvent(event)) {
                if (action == MotionEvent.ACTION_UP) {
                    // tup up after scrolling
                    post(startAnimation);
                }
            }
            return false;
        }
    };

    OnClickListener clickListener = new OnClickListener() {
        public void onClick(View v) {
            if (mBringToFront) {
                bringToFront();
            }
            if (initChange()) {
                post(startAnimation);
            }
        }
    };

    public boolean initChange() {
        if (mState != State.READY) {
            // we are animating or just about to animate
            return false;
        }
        mState = State.ABOUT_TO_ANIMATE;
        mIsShrinking = mContent.getVisibility() == VISIBLE;
        if (!mIsShrinking) {
            // this could make flicker so we test mState in dispatchDraw()
            // to see if is equal to ABOUT_TO_ANIMATE
            mContent.setVisibility(VISIBLE);
        }
        return true;
    }

    Runnable startAnimation = new Runnable() {
        public void run() {

            callPanListener();

            // this is why we post this Runnable couple of lines above:
            // now its save to use mContent.getHeight() && mContent.getWidth()
            TranslateAnimation animation;
            int fromXDelta = 0, toXDelta = 0, fromYDelta = 0, toYDelta = 0;
            if (mState == State.FLYING) {
                mIsShrinking = (mPosition == TOP || mPosition == LEFT) ^ (mVelocity > 0);
            }
            int calculatedDuration;
            if (mOrientation == VERTICAL) {
                int height = mContentHeight;
                if (!mIsShrinking) {
                    fromYDelta = mPosition == TOP? -height : height;
                } else {
                    toYDelta = mPosition == TOP? -height : height;
                }
                if (mState == State.TRACKING) {
                    if (Math.abs(mTrackY - fromYDelta) < Math.abs(mTrackY - toYDelta)) {
                        mIsShrinking = !mIsShrinking;
                        toYDelta = fromYDelta;
                    }
                    fromYDelta = (int) mTrackY;
                } else
                if (mState == State.FLYING) {
                    fromYDelta = (int) mTrackY;
                }
                // for FLYING events we calculate animation duration based on flying velocity
                // also for very high velocity make sure duration >= 20 ms
                if (mState == State.FLYING && mLinearFlying) {
                    calculatedDuration = (int) (1000 * Math.abs((toYDelta - fromYDelta) / mVelocity));
                    calculatedDuration = Math.max(calculatedDuration, 20);
                } else {
                    calculatedDuration = mDuration * Math.abs(toYDelta - fromYDelta) / mContentHeight;
                }
            } else {
                int width = mContentWidth;
                if (!mIsShrinking) {
                    fromXDelta = mPosition == LEFT? -width : width;
                } else {
                    toXDelta = mPosition == LEFT? -width : width;
                }
                if (mState == State.TRACKING) {
                    if (Math.abs(mTrackX - fromXDelta) < Math.abs(mTrackX - toXDelta)) {
                        mIsShrinking = !mIsShrinking;
                        toXDelta = fromXDelta;
                    }
                    fromXDelta = (int) mTrackX;
                } else
                if (mState == State.FLYING) {
                    fromXDelta = (int) mTrackX;
                }
                // for FLYING events we calculate animation duration based on flying velocity
                // also for very high velocity make sure duration >= 20 ms
                if (mState == State.FLYING && mLinearFlying) {
                    calculatedDuration = (int) (1000 * Math.abs((toXDelta - fromXDelta) / mVelocity));
                    calculatedDuration = Math.max(calculatedDuration, 20);
                } else {
                    calculatedDuration = mDuration * Math.abs(toXDelta - fromXDelta) / mContentWidth;
                }
            }

            mTrackX = mTrackY = 0;
            if (calculatedDuration == 0) {
                mState = State.READY;
                if (mIsShrinking) {
                    mContent.setVisibility(GONE);
                }
                postProcess();
                return;
            }

            animation = new TranslateAnimation(fromXDelta, toXDelta, fromYDelta, toYDelta);
            animation.setDuration(calculatedDuration);
            if (mState == State.FLYING && mLinearFlying) {
                animation.setInterpolator(new LinearInterpolator());
            } else
            if (mInterpolator != null) {
                animation.setInterpolator(mInterpolator);
            }
            startAnimation(animation);
        }
    };

    @Override
    protected void onAnimationEnd() {
        super.onAnimationEnd();
        mState = State.READY;
        if (mIsShrinking) {
            mContent.setVisibility(GONE);
        }
        postProcess();
    }

    @Override
    protected void onAnimationStart() {
        super.onAnimationStart();
        mState = State.ANIMATING;
    }

    private void postProcess() {
        if (mIsShrinking && mClosedHandle != null) {
            mHandle.setBackgroundDrawable(mClosedHandle);
        } else
        if (!mIsShrinking && mOpenedHandle != null) {
            mHandle.setBackgroundDrawable(mOpenedHandle);
        }
        // invoke listener if any
        callPanListener();
    }
    public void callPanListener()
    {
        if (panelListener != null) {
            if (mIsShrinking) {
                panelListener.onPanelClosed(Panel.this);
            } else {
                panelListener.onPanelOpened(Panel.this);
            }
        }
    }

    class PanelOnGestureListener implements OnGestureListener {
        float scrollY;
        float scrollX;
        public void setScroll(int initScrollX, int initScrollY) {
            scrollX = initScrollX;
            scrollY = initScrollY;
        }
        public boolean onDown(MotionEvent e) {
            scrollX = scrollY = 0;
            callPanListener();
            initChange();
            return true;
        }
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            mState = State.FLYING;
//          velocityX=400;
//          velocityY=400;
            mVelocity = mOrientation == VERTICAL? velocityY : velocityX;
//          mVelocity=400;
            post(startAnimation);
            return true;
        }
        public void onLongPress(MotionEvent e) {
            // not used
        }
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            mState = State.TRACKING;
            float tmpY = 0, tmpX = 0;
            if (mOrientation == VERTICAL) {
                scrollY -= distanceY;
                if (mPosition == TOP) {
                    tmpY = ensureRange(scrollY, -mContentHeight, 0);
                } else  {
                    tmpY = ensureRange(scrollY, 0, mContentHeight);
                }
            } else {
                scrollX -= distanceX;
                if (mPosition == LEFT) {
                    tmpX = ensureRange(scrollX, -mContentWidth, 0);
                } else {
                    tmpX = ensureRange(scrollX, 0, mContentWidth);
                }
            }
            if (tmpX != mTrackX || tmpY != mTrackY) {
                mTrackX = tmpX;
                mTrackY = tmpY;
                invalidate();
            }
            return true;
        }
        public void onShowPress(MotionEvent e) {
            // not used
        }
        public boolean onSingleTapUp(MotionEvent e) {
            // not used
            return false;
        }
    }
}

主.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:panel="http://schemas.android.com/apk/res/packagename"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"">

<LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:gravity="center_horizontal" >

        <packagename.Panel
            android:id="@+id/panel_menu"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            panel:animationDuration="1000"
            panel:closedHandle="#0000FF"
            panel:content="@+id/panelContent"
            panel:handle="@+id/panelHandle"
            panel:linearFlying="false"
            panel:openedHandle="#0000FF"
            android:paddingTop="4dip"
            panel:position="bottom" >

            <Button
                android:id="@+id/panelHandle"
                android:layout_width="33dp"
                android:layout_height="33dp"
                android:layout_gravity="center_horizontal"
                android:text="^"
                android:textColor="@android:color/white" />

            <RelativeLayout
                android:id="@+id/panelContent"
                android:layout_width="fill_parent"
                android:layout_height="50dp"
                android:background="#0000FF" >
            </RelativeLayout>
        </packagename.Panel>
</RelativeLayout>

属性.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="Panel">
        <!-- Defines panel animation duration in ms. -->
        <attr name="animationDuration" format="integer" />
        <!-- Defines panel position on the screen. -->
        <attr name="position">
            <!-- Panel placed at top of the screen. -->
            <enum name="top" value="0" />
            <!-- Panel placed at bottom of the screen. -->
            <enum name="bottom" value="1" />
            <!-- Panel placed at left of the screen. -->
            <enum name="left" value="2" />
            <!-- Panel placed at right of the screen. -->
            <enum name="right" value="3" />
        </attr>
        <!-- Identifier for the child that represents the panel's handle. -->
        <attr name="handle" format="reference" />
        <!-- Identifier for the child that represents the panel's content. -->
        <attr name="content" format="reference" />
        <!-- Defines if flying gesture forces linear interpolator in animation. -->
        <attr name="linearFlying" format="boolean" />
        <!-- Defines size relative to parent (must be in form: nn%p). -->
        <attr name="weight" format="fraction" />
        <!-- Defines opened handle (drawable/color). -->
        <attr name="openedHandle" format="reference|color" />
        <!-- Defines closed handle (drawable/color). -->
        <attr name="closedHandle" format="reference|color" />
    </declare-styleable>

</resources>

要在您的 Activity 中使用它

示例 Activity .java

public class SampleActivity extends Activity implements OnPanelListener {

public Panel samplePanel;
  @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.panel_main)_layout;

        samplePanel = (Panel) findViewById(R.id.panel_id);
        samplePanel.setOnPanelListener(this);
        samplePanel.setInterpolator(new ExpoInterpolator(Type.OUT));

     }

     public void onPanelClosed(Panel panel) {}//Interface Listener
     public void onPanelOpened(Panel panel) {}//Interface Listener
}

关于android - 如何在 Android 中创建幻灯片布局动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13678595/

有关android - 如何在 Android 中创建幻灯片布局动画?的更多相关文章

  1. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  2. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  3. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  4. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  5. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

  6. ruby - 如何在 Ruby 中拆分参数字符串 Bash 样式? - 2

    我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"

  7. ruby - 如何在 Lion 上安装 Xcode 4.6,需要用 RVM 升级 ruby - 2

    我实际上是在尝试使用RVM在我的OSX10.7.5上更新ruby,并在输入以下命令后:rvminstallruby我得到了以下回复:Searchingforbinaryrubies,thismighttakesometime.Checkingrequirementsforosx.Installingrequirementsforosx.Updatingsystem.......Errorrunning'requirements_osx_brew_update_systemruby-2.0.0-p247',pleaseread/Users/username/.rvm/log/138121

  8. ruby-on-rails - 如何在 ruby​​ 交互式 shell 中有多行? - 2

    这可能是个愚蠢的问题。但是,我是一个新手......你怎么能在交互式ruby​​shell中有多行代码?好像你只能有一条长线。按回车键运行代码。无论如何我可以在不运行代码的情况下跳到下一行吗?再次抱歉,如果这是一个愚蠢的问题。谢谢。 最佳答案 这是一个例子:2.1.2:053>a=1=>12.1.2:054>b=2=>22.1.2:055>a+b=>32.1.2:056>ifa>b#Thecode‘if..."startsthedefinitionoftheconditionalstatement.2.1.2:057?>puts"f

  9. ruby-on-rails - 如何在我的 Rails 应用程序 View 中打印 ruby​​ 变量的内容? - 2

    我是一个Rails初学者,但我想从我的RailsView(html.haml文件)中查看Ruby变量的内容。我试图在ruby​​中打印出变量(认为它会在终端中出现),但没有得到任何结果。有什么建议吗?我知道Rails调试器,但更喜欢使用inspect来打印我的变量。 最佳答案 您可以在View中使用puts方法将信息输出到服务器控制台。您应该能够在View中的任何位置使用Haml执行以下操作:-puts@my_variable.inspect 关于ruby-on-rails-如何在我的R

  10. ruby - 如何在 Rails 4 中使用表单对象之前的验证回调? - 2

    我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser

随机推荐