可以在Android上没有ToolBar的情况下制作视差效果吗?

时间:2016-03-23 17:23:41

标签: java android parallax

我找了很长时间(也看第三方图书馆)制作某种“视差”,但没有Toolbar,我所见过的只是与Toolbar合作,但是这不符合我的最佳利益,因为我在整个应用程序中删除了Toolbar

我按照这个例子:https://www.youtube.com/watch?v=HO82ES_RiSQ但它并没有说服我......

有谁可以解决这个问题?我想知道如何在不使用Toolbar

的情况下进行视差

提前致谢

1 个答案:

答案 0 :(得分:4)

您只需三步即可完成:)

  1. compile 'com.github.ksoichiro:android-observablescrollview:1.6.0'添加到 build.gradle project on github)中的依赖项
  2. 使用ImageView,可滚动内容和 ObservableScrollView 作为容器创建布局。

    <强> activity_layout.xml

    <?xml version="1.0" encoding="utf-8"?>
    <com.github.ksoichiro.android.observablescrollview.ObservableScrollView      
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/observable_scrollview"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
       <LinearLayout
           android:layout_width="wrap_content"
           android:layout_height="match_parent"
           android:orientation="vertical">
    
           <ImageView
               android:id="@+id/image_view"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:adjustViewBounds="true"
               android:src="@drawable/example" />
           <View
               android:id="@+id/your_content"
               android:layout_width="wrap_content"
               android:layout_height="600dp"
               android:background="@android:color/black" />
       </LinearLayout>
    </com.github.ksoichiro.android.observablescrollview.ObservableScrollView>
    
  3. 在ObservableScrollView中设置 ObservableScrollViewCallbacks ,并在onScrollChange方法中将y轴转换为ImageView

    public class MainActivity extends AppCompatActivity implements  ObservableScrollViewCallbacks {
        private ImageView imageView;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             setContentView(R.layout.activity_layout);
             ObservableScrollView observableScrollView = (ObservableScrollView) findViewById(R.id.observable_scrollview);
             observableScrollView.setScrollViewCallbacks(this);
             imageView = (ImageView) findViewById(R.id.image_view);
        }
    
        @Override
        public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {
             imageView.setTranslationY(scrollY / 2);
        } 
    }
    
  4. 非常重要的是 imageView.setTranslationY(scrollY / 2); ,这意味着您的ImageView滚动速度比滚动内容慢两倍。

    以下是它的样子:

    Parallax image