Android ViewFlipper的触碰动画,如新闻和天气

来源:互联网 发布:nx软件基础教程 编辑:程序博客网 时间:2024/05/17 23:47

引言

我们将在本教程中学习解决Android工程的一个常见问题,如需获取关于Android工程的更多信息,我建议你下载 ADT Android 插件和 Eclipse. 我们先从 Android 开发的一些基础开始。

背景

Android开发需要三样很重要的东西: Android Sdk (你可以从这里下载), 工程编辑器(我推荐使用Eclipse) 和 Android 的 Eclipse 插件

环境准备好后就可以阅读本教程了

第一次打开 Android SDK 时,你需要创建一个虚拟设备,我建议使用 Target the Android 1.6 Api Level 4 创建一个普通设备,然后将你需要的硬件特征添加进去,例如:支持SD卡,Accellerometer,支持相机等。创建Android虚拟设备时遇到任何困难,请访问此链接

创建 Eclipse 工程

按照下列步骤在 Eclipse 中创建 Android 工程:

  1. 选择 File > New > Project.
  2. 选择 Android > Android Project, 并点击 Next.
  3. 选择工程的内容:
    • 输入工程的名称,这是你创建的工程所在文件夹的名称
    • 在 Contents 下面,选择 Create new project in workspace. 选择工程工作区的位置
    • 在 Target 下面,选择一个Android target 用作工程的 Build Target. Build Target 指定你希望应用被创建的 Android 平台。除非你知道你要使用SDK最近引入的新的APIs,否则你应当选择一个尽可能低版本平台的 target,如Android 1.6平台注意:你可以随时改变工程的 Build Target:在 Package Explorer 中右键点击你的工程,选择Properties,选择 Android,然后选择你想要的 Project Target
    • 在 Properties 下面,填写所有需要的字段
      • 输入应用的名称,这个名称将出现在Android设备上,并且是人类可读的
      • 输入组件的名称,这是将要放置源代码组件的命名空间(命名规则遵循 Java 编程语言的组件命名规则)
      • 选择 Create Activity(可选,通常都选择),输入一个主 Activity 类的名称
      • 输入一个 Min SDK Version. 这是一个整数,用来表示运行你的应用所需要的最低 API Level。输入后会在 Android Manifest 文件的  中自动设置 minSdkVersion 属性。如果你确定不了合适的 API Level,复制Build Target 列出的 API Level
  4. 点击 Finish.

完成之后,ADT将创建下列文件夹和文件:

  • src/: 包含存根类 Activity Java 文件,所有其他Java文件都在这里
  • :包含你用来创建应用的 android.jar 文件,由你在 New Project Wizard 中所选择的 build target 决定。
  • gen/: 这里包含 ADT 生成的 Java 文件,如你的 R.java 文件和 AIDL文件创建的接口(这是一个自动的类)
  • assets/: 这是空的,你可以用它来存储原始资产文件
  • res/: 用于存储应用程序资源的文件夹,如可拖拽文件,构图文件,字符串值等
  • AndroidManifest.xml: 你工程的 Android Manifest
  • default.properties: 这个文件包含工程的设置,如 build target,它是工程所必须的,应该在 Source Revision Control 系统中维护。不要对其进行人工编辑——要编辑工程的属性,右键点击工程的文件夹,并选择“Properties”

在本教程中,我们只使用两个文件夹:src/  res/, 我们现在从普遍问题的解决实例开始

如何通过触碰事件来滑动两个(或更多的)布局 如新闻和天气

现在你已经准备好了,模拟图形效果是我们在 Android 开发中首先需要做的几件事之一。所以,用的最多、效果最好的动画/事件之一是用手指滑动窗口,从一个活动转向另一个。 完成这项工作需要一些 java 代码和一些 XML 布局文件中的提示.

从 XML 布局文件开始

从路径 res/layout/ 打开 main.xml (或者其他布局文件)并输入这些行:

1234567891011121314151617181920212223242526272829303132
<ViewFlipper    android:layout_margin="6dip"    android:id="@+id/layoutswitcher"    android:layout_width="fill_parent"    android:layout_height="fill_parent">    <LinearLayout        android:layout_width="fill_parent"        android:layout_height="fill_parent">        <TextView            android:layout_height="wrap_content"            android:id="@+id/firstpanel"            android:paddingTop="10dip"            android:text="my first panel"            android:layout_width="fill_parent"            android:layout_weight="1"            android:textStyle="bold" >        </TextView>    </LinearLayout>    <LinearLayout        android:layout_width="fill_parent"        android:layout_height="fill_parent">        <TextView            android:layout_height="wrap_content"            android:id="@+id/secondpanel"            android:paddingTop="10dip"            android:text="my second panel"            android:layout_width="fill_parent"            android:layout_weight="1"            android:textStyle="bold" >        </TextView>    </LinearLayout></ViewFlipper>

正如你看到的,我加入了一个 ViewFlipper,两个 LinearLayout,并为每个内部布局加入 simpletextview,当你可以定制你想要的两个内部布局的类型时,如果你想加入用来开关内部布局的工具栏,则第一步在创建合适的开关布局时是必需的。

第二步: Java 代码(通过触碰开关布局)

现在从 src/ 打开你的主类,在类的开始声明这两个变量:

12
    private ViewFlipper vf;    private float oldTouchValue;

第一个变量VF用来控制 ViewFlipper,触碰事件需要第二个变量,现在将 viewflipper 附到类中:

12345
     public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        <em>....</em><strong>vf = (ViewFlipper) findViewById(R.id.switchlayout);</strong>     }

现在我们有一个声明过的 viewflipper,进入本教程的最后几步。

触碰事件

这款新的移动电话最重要的特征是触摸屏系统,正如 iPhone 的 apps 或者其他触摸设备一样,用户喜欢用手指在不同的活动之间进行切换。在 Android 开发中,你可以用两种方式附加触摸事件,”应用 touchlistener” 或者重写主函数声明一个 onTouchEvent

在本示例中,我们使用第二种方案:

123456789101112131415161718192021222324252627282930
    @Override    public boolean onTouchEvent(MotionEvent touchevent) {        switch (touchevent.getAction())        {            case MotionEvent.ACTION_DOWN:            {                oldTouchValue = touchevent.getX();                break;            }            case MotionEvent.ACTION_UP:            {                if(this.searchOk==false) return false;                float currentX = touchevent.getX();                if (oldTouchValue < currentX)                {                    vf.setInAnimation(AnimationHelper.inFromLeftAnimation());                    vf.setOutAnimation(AnimationHelper.outToRightAnimation());                    vf.showNext();                }                if (oldTouchValue > currentX)                {                    vf.setInAnimation(AnimationHelper.inFromRightAnimation());                    vf.setOutAnimation(AnimationHelper.outToLeftAnimation());                    vf.showPrevious();                }            break;            }        }        return false;    }

正如你看到的,当用户第一次触摸设备时,一个浮点型变量(oldTouchValue)将读入用户手指位置的 X 坐标,然后当用户释放手指时,检查事件的新位置决定用户是向前还是向后(oldTouchValue < currentX, oldTouchValue > currentX). 要改变布局的代码是相同的,但我使用不同的动画来表示用户想向前还是向后,关于动画和 AnimationHelper的详细解释参见代码:

123456789101112131415161718192021222324252627282930313233343536373839
//对于向前的运动public static Animation inFromRightAnimation() {     Animation inFromRight = new TranslateAnimation(    Animation.RELATIVE_TO_PARENT,  +1.0f, Animation.RELATIVE_TO_PARENT,  0.0f,    Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f    );    inFromRight.setDuration(350);    inFromRight.setInterpolator(new AccelerateInterpolator());    return inFromRight;    }    public static Animation outToLeftAnimation() {    Animation outtoLeft = new TranslateAnimation(     Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  -1.0f,     Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f    );    outtoLeft.setDuration(350);    outtoLeft.setInterpolator(new AccelerateInterpolator());    return outtoLeft;    }    // 对于向后的运动    public static Animation inFromLeftAnimation() {    Animation inFromLeft = new TranslateAnimation(    Animation.RELATIVE_TO_PARENT,  -1.0f, Animation.RELATIVE_TO_PARENT,  0.0f,    Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f    );    inFromLeft.setDuration(350);    inFromLeft.setInterpolator(new AccelerateInterpolator());    return inFromLeft;    }    public static Animation outToRightAnimation() {    Animation outtoRight = new TranslateAnimation(     Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  +1.0f,     Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f    );    outtoRight.setDuration(350);    outtoRight.setInterpolator(new AccelerateInterpolator());    return outtoRight;    }

你可以将这些函数放置在静态类中(正如我所做的)或者在你的类中声明它们

结论

现在你有了基类和事件来捕捉从右向左(show.previous)和从左向右(show.next)的触摸运动,以及能够解释四种动画运动的代码和一个简单的布局。我建议用两个以上的布局和更复杂的环境做进一步测试。本教程只是 Android 能力的一个示例,我想你可以找到更加强大的解决方案!

许可

这篇文章及相关的代码、文件遵守The Code Project Open License (CPOL)的许可

关于作者

Francesco Lo Truglio(FLT.lab)

Web开发者和工程管理者,FLT.lab的创始人

JsMaps Api 认证的Google开发者

原文链接:http://www.codeproject.com/KB/android/ViewFlipper_Animation.aspx

原作者:Francesco Lo Truglio

原文:

Android: ViewFlipper Touch Animation like News & Weather

Introduction

In thie tutorial we can learn how to solve a common problem in Android project, to have more info regarding Android project I suggest to you to download the ADT Android Pluglins and Eclipse. Let’s start with a little basics around Android development.

Background

To begin the android develompent you need tree important thins: The Android Sdk (you can download it here), A Project Editor (i suggest eclipse) and the Android eclipse plugin.

When you have the environment ready you can start with this tutorial.

When you open for the first time the Android SDK you need to create a virtual device, I suggest to create a common device using as Target the Android 1.6 Api Level 4 and then you need to add the hardware features that you need in your environment, for example: SD Card Support, Accellerometer, Camera Support etc. if you need help to start up an android virtual device follow this link.

Start the Ecplise Project

Follow these simple step to create an Android Project in eclipse:

  1. Select File > New > Project.
  2. Select Android > Android Project, and click Next.
  3. Select the contents for the project:
    • Enter a Project Name. This will be the name of the folder where your project is created.
    • Under Contents, select Create new project in workspace. Select your project workspace location.
    • Under Target, select an Android target to be used as the project’s Build Target. The Build Target specifies which Android platform you’d like your application built against.Unless you know that you’ll be using new APIs introduced in the latest SDK, you should select a target with the lowest platform version possible, such as Android 1.6.Note: You can change your the Build Target for your project at any time: Right-click the project in the Package Explorer, selectProperties, select Android and then check the desired Project Target.
    • Under Properties, fill in all necessary fields.
      • Enter an Application name. This is the human-readable title for your application — the name that will appear on the Android device.
      • Enter a Package name. This is the package namespace (following the same rules as for packages in the Java programming language) where all your source code will reside.
      • Select Create Activity (optional, of course, but common) and enter a name for your main Activity class.
      • Enter a Min SDK Version. This is an integer that indicates the minimum API Level required to properly run your application. Entering this here automatically sets the minSdkVersion attribute in the  of your Android Manifest file. If you’re unsure of the appropriate API Level to use, copy the API Level listed for the Build Target you selected in the Target tab.
  4. Click Finish.

when you are ready the ADT creates for you the following folders and files:

  • src/: Includes any Activity Java file. All other Java files for your application go here.
  • : Includes the android.jar file that your application will build against. This is determined by the build target that you have chosen in the New Project Wizard
  • gen/: This contains the Java files generated by ADT, such as your R.java file and interfaces created from AIDL files (this is an automatic class)..
  • assets/: This is empty. You can use it to store raw asset files.
  • res/: A folder for your application resources, such as drawable files, layout files, string values, etc.
  • AndroidManifest.xml: The Android Manifest for your project.
  • default.properties: This file contains project settings, such as the build target. This files is integral to the project, as such, it should be maintained in a Source Revision Control system. It should never be edited manually — to edit project properties, right-click the project folder and select “Properties”.

In this tutorial we use only two folder: src/ and res/, now start with the sample solution to the common problem

How to Slide Two (or more) Layout like the News & Weather by Touch Event

Now that you are ready with Android, one of the first things we try to in Android development is to emulate the graphics effect that have the best applications. So, one of the animations/events mostly used and highly effective is the sliding window from one activity to another by using the fing. To do this we need a little bit of java code and some tips in our XML layout.

Begin from the XML Layout File

Open from res/layout/ the main.xml (or some other layout file) and put this lines:

1234567891011121314151617181920212223242526272829303132
<ViewFlipper    android:layout_margin="6dip"    android:id="@+id/layoutswitcher"    android:layout_width="fill_parent"    android:layout_height="fill_parent">    <LinearLayout        android:layout_width="fill_parent"        android:layout_height="fill_parent">        <TextView            android:layout_height="wrap_content"            android:id="@+id/firstpanel"            android:paddingTop="10dip"            android:text="my first panel"            android:layout_width="fill_parent"            android:layout_weight="1"            android:textStyle="bold" >        </TextView>    </LinearLayout>    <LinearLayout        android:layout_width="fill_parent"        android:layout_height="fill_parent">        <TextView            android:layout_height="wrap_content"            android:id="@+id/secondpanel"            android:paddingTop="10dip"            android:text="my second panel"            android:layout_width="fill_parent"            android:layout_weight="1"            android:textStyle="bold" >        </TextView>    </LinearLayout></ViewFlipper>

As you can see, I add one ViewFlipper, two LinearLayout and for each inner layout a simpletextview, this first step is ncessary to create a proper switching layout, after you can customize as you want the style of the two inner layout and if you want add a toolbar to switch around the inner layout.

Second step: Java Code (Switch Layout by Touch)

Now open your main class from src/ and in the begin of the class declare these two variables:

12
    private ViewFlipper vf;    private float oldTouchValue;

The first Variable (VF) is needed to constrol the ViewFlipper and the second one is needed to the touch event, now attach the viewflipper to the class :

12345
     public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        <em>....</em><strong>vf = (ViewFlipper) findViewById(R.id.switchlayout);</strong>     }

Now we have a declared viewflipper and can proceed to the last step of this simple tutorial.

The Touch Event

One of the most important feature of this new mobile phone is the Touch Screen system and like iPhone apps or other touching device the user prefer to switch among the activies by their fingers. In Android develpment to attach a touch event you can do two things “implement the touchlistener” or declare am onTouchEventby overriding the main method.

In this sample we use the second case, take a look of the following code and then to the explaination:

123456789101112131415161718192021222324252627282930
    @Override    public boolean onTouchEvent(MotionEvent touchevent) {        switch (touchevent.getAction())        {            case MotionEvent.ACTION_DOWN:            {                oldTouchValue = touchevent.getX();                break;            }            case MotionEvent.ACTION_UP:            {                if(this.searchOk==false) return false;                float currentX = touchevent.getX();                if (oldTouchValue < currentX)                {                    vf.setInAnimation(AnimationHelper.inFromLeftAnimation());                    vf.setOutAnimation(AnimationHelper.outToRightAnimation());                    vf.showNext();                }                if (oldTouchValue > currentX)                {                    vf.setInAnimation(AnimationHelper.inFromRightAnimation());                    vf.setOutAnimation(AnimationHelper.outToLeftAnimation());                    vf.showPrevious();                }            break;            }        }        return false;    }

As you can see, when the user touch for the first time the device a fill the float variable (oldTouchValue) with the X position of his finger, then when the user release his finger I check the new position of the event to decide if the user want to go next or previous ( oldTouchValue  currentX). To change the layout the code is the same but I use different animation if the user want to go next or previous, for more explaining about the animation and the AnimationHelper I put this sample code:

123456789101112131415161718192021222324252627282930313233343536373839
//for the previous movementpublic static Animation inFromRightAnimation() {     Animation inFromRight = new TranslateAnimation(    Animation.RELATIVE_TO_PARENT,  +1.0f, Animation.RELATIVE_TO_PARENT,  0.0f,    Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f    );    inFromRight.setDuration(350);    inFromRight.setInterpolator(new AccelerateInterpolator());    return inFromRight;    }    public static Animation outToLeftAnimation() {    Animation outtoLeft = new TranslateAnimation(     Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  -1.0f,     Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f    );    outtoLeft.setDuration(350);    outtoLeft.setInterpolator(new AccelerateInterpolator());    return outtoLeft;    }    // for the next movement    public static Animation inFromLeftAnimation() {    Animation inFromLeft = new TranslateAnimation(    Animation.RELATIVE_TO_PARENT,  -1.0f, Animation.RELATIVE_TO_PARENT,  0.0f,    Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f    );    inFromLeft.setDuration(350);    inFromLeft.setInterpolator(new AccelerateInterpolator());    return inFromLeft;    }    public static Animation outToRightAnimation() {    Animation outtoRight = new TranslateAnimation(     Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  +1.0f,     Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f    );    outtoRight.setDuration(350);    outtoRight.setInterpolator(new AccelerateInterpolator());    return outtoRight;    }

You can decide to put these method in a static class (like me) or to declare they in your class.

Conclusion

Now you have the base class and the event to catch the touch movement from right to left ( show.previous) and from left to right ( show.next), a simple code that explain the four animation movement amd a simple layout to try this. I would suggest to do further testing with more than two layout and with more complex content. This is only a sample of the Android ability, but I think that you can find more powerful solutions!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Francesco Lo Truglio(FLT.lab)

Web Developer and Project Manager, founder of FLT.lab
Google Developer Certified on JsMaps Api

原创粉丝点击