2012-05-06 2 views
5

Я хотел бы добавить что-то обратно на этот ОЧЕНЬ полезный сайт, так что это не вопрос, а скорее мое решение этой проблемы. Я также хотел бы добавить, что это решение было подкреплено поддержкой формы с этого сайта и многих других, поэтому оно представляет собой совместные усилия многих других разработчиков. К ним я говорю спасибо!Управление страницей на Android-странице, например, управление страницей на iPhone

ВОПРОС: «Как вы можете воссоздать горизонтальные scrollView аспекты iPhone-приложений и связанный с ними контроль страницы в среде Android?»

Это связано с тем, что я хотел показать шаги в рецепте, связанный с ним метод для каждого шага и необходимые ингредиенты в одном прокрутке. Я также хотел, чтобы элемент управления страницы отображался пользователю, где они были на шагах, и позволяет им перейти на какой-либо конкретный шаг.

Эта часть моего приложения отображает шаги в рецепте. Каждый шаг отображается на странице и состоит из трех компонентов. Идентификатор этапа (т. Е. ШАГ 1, ШАГ 2), способ и ингредиенты, необходимые для этапа.

Ниже в разделе рецепта отображается элемент управления страницы, показывающий, какая страница активна и может использоваться для перехода на определенные страницы. Вы заметите, что элемент управления страницы имеет кнопки изображения, а два изображения - простые круги, один для не выбранной страницы (page.png) и один для выбранной страницы (page_selected.png)

Когда создается действие, шаги для выбранного рецепта извлекаются из данных и секции скроллера, созданных путем добавления представления для каждого шага в рецепте. Когда вы проводите скроллер вид привязывается к следующей или предыдущей странице, и на дисплее пейджера обновляется, чтобы указать, на какой странице вы находитесь на

Первые 3 макеты XML (разрешения/макет)

recipe.xml

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

<RelativeLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" > 

<!--Scroller section--> 

    <HorizontalScrollView 
     android:id="@+id/scroll_view" 
     android:layout_width="match_parent" 
     android:layout_height="320dp" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentTop="true" 
     android:layout_marginTop="100dp" > 

      <LinearLayout 
       android:id="@+id/methodScrollView" 
       android:layout_width="match_parent" 
       android:layout_height="match_parent" 
       android:orientation="horizontal" > 
      </LinearLayout> 

    </HorizontalScrollView> 

<!-- pager section --> 

    <LinearLayout 
     android:id="@+id/pager" 
     android:layout_width="match_parent" 
     android:layout_height="20dp" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentRight="true" 
     android:layout_alignParentTop="true" 
     android:layout_marginLeft="20dp" 
     android:layout_marginRight="20dp" 
     android:layout_marginTop="430dp" 
     android:gravity="center" 
     android:orientation="horizontal" > 

    </LinearLayout> 

</RelativeLayout> 

recipesscroll.xml (вид, который будет добавлен к секции скроллера для каждого шага рецепта. Обратите внимание, что раздел скроллера имеет onTouchlistner в recipeViewController.java для обработки страницы прокрутки)

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/recipeScroll" 
    android:layout_width="320dp" 
    android:layout_height="320dp" 
    android:gravity="center_vertical" > 

    <TextView 
    android:id="@+id/method" 
    style="@style/scrollMethod" 
    android:layout_width="wrap_content" 
    android:layout_height="200dp" 
    android:layout_alignParentTop="true" 
    android:text="Method" /> 

    <TextView 
    android:id="@+id/ingredients" 
    style="@style/scrollIngredients" 
    android:layout_width="wrap_content" 
    android:layout_height="120dp" 
    android:layout_alignParentTop="true" 
    android:text="Ingredients" /> 

    <TextView 
    android:id="@+id/methodStep" 
    style="@style/scrollStep" 
    android:layout_width="wrap_content" 
    android:layout_height="20dp" 
    android:layout_alignParentTop="true" 
    android:text="Step" /> 

</RelativeLayout> 

recipiespager.xml (вид, который будет добавлен в раздел пейджера для каждого шага рецепта. Обратите внимание, что каждый из них будет иметь событие OnClick в recipeViewController.java, который будет прокручивать для конкретной страницы, выбранной в элементе управления пейджером)

<?xml version="1.0" encoding="utf-8"?> 
<Button xmlns:android="http://schemas.android.com/apk/res/android" 
      style="@style/pageButton" 
      android:layout_marginLeft="10dp" 
      android:layout_width="16dp" 
      android:layout_height="16dp" 
      android:onClick="selectPage"> 

</Button> 

Это все собрались в recipeViewController.java

//my package name change this to yours 
package com.infactdata.spinAdinner; 

import java.util.ArrayList; 

//DataModel is the model for my data change this to yours or ignore 
because it is just away of holding the data that will populate the views 
import com.infactdata.plist.DataModel; 

import android.content.res.Resources; 
import android.graphics.Typeface; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.LayoutInflater; 
import android.view.MotionEvent; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.view.View.OnTouchListener; 
import android.widget.Button; 
import android.widget.HorizontalScrollView; 
import android.widget.ImageView; 
import android.widget.LinearLayout; 
import android.widget.RelativeLayout; 
import android.widget.TableLayout; 
import android.widget.TableRow; 
import android.widget.TextView; 

public class RecipeViewController extends RootViewController { 
    private DataModel currentData; 
    HorizontalScrollView h_scroll; 
    int numberOfPages = 0; 
    int thePage; 
    int otherPage; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     //first of the xml files 
     setContentView(R.layout.recipe); 

     //reference to my global variables 
     GlobalClass global = (GlobalClass)getApplicationContext(); 

     //because I wanted a particular type face 
     Typeface face=Typeface.createFromAsset(getAssets(), "fonts/trebucit.ttf"); 

     //VERY IMPORTANT because we need to use this to add the content to the scroll 
     and pager sections 
     LayoutInflater inflater = getLayoutInflater(); 

     //current data held a dataModel 
     currentData = global.getCurrent(); 

     currentName.setText(currentData.getName()); 

     String imageFile = currentData.getImage(); 
     Resources r = getResources(); 

     int res = r.getIdentifier(imageFile, "drawable", "com.infactdata.spinAdinner"); 
     image.setImageResource(res); 

     //recources that change the pager indicators to different images 
     thePage = r.getIdentifier("page_selected", "drawable","com.infactdata.spinAdinner"); 
     otherPage = r.getIdentifier("page", "drawable", "com.infactdata.spinAdinner"); 

     //Get the method(ArrayList) out of the currentData(DataModel). This is the array of 
     data that will fill the added view with different content (ie. the specific 
     instructions for the recipe step. This could be your own data array. 

     ArrayList<String[]> method = new ArrayList<String[]>(); 
     method = currentData.getMethod(0); 
     numberOfPages = method.size(); 

     //now to build the views by adding the content and then adding the text for that 
     content that reflects the instructions for the step in the recipe 

     for(int i = 0; i < method.size(); i++){ 

      String[] methodStep = method.get(i); 

      //find the scroll view 
      LinearLayout scroll = (LinearLayout) findViewById(R.id.methodScrollView); 

      //find the recipe scroller. the second xml file 
      RelativeLayout step = (RelativeLayout)findViewById(R.id.recipeScroll); 

      //add the recipe step (step) to the scrollview (scroll) 
      step = (RelativeLayout)inflater.inflate(R.layout.recipescroll, scroll, false); 

      //add the instructions for this step in the recipe 
      TextView stage = (TextView)step.findViewById(R.id.methodStep); 
      stage.setText(methodStep[0].toString()); 
      stage.setTypeface(face); 

      TextView methodText = (TextView)step.findViewById(R.id.method); 
      methodText.setText(methodStep[1].toString()); 
      methodText.setTypeface(face); 

      TextView ingredients = (TextView)step.findViewById(R.id.ingredients); 
      ingredients.setText(methodStep[2].toString()); 
      ingredients.setTypeface(face); 

      //create method step and add to scroll 
      scroll.addView(step); 

      //pager setup is a duplicate of the above 
      //find the pager 
      LinearLayout pager = (LinearLayout) findViewById(R.id.pager); 

      //find the pager button. the third xml file 
      Button page = (Button)inflater.inflate(R.layout.recipespager, pager, false); 

      //give each button it own ID. This will be used to test which button should be highlighted and used to move to a specific page. This is because the ID is equal to the page number (0 based of course) 
      page.setId(i); 

      //because this is a fresh construction we will be on page 0 so highlight that button 
      if (i == 0){ 
       page.setBackgroundResource(thePage); 
      } 

      //create page control and add to pager 
      pager.addView(page); 
     } 

     //create the onTouch controls 

     h_scroll = (HorizontalScrollView) findViewById(R.id.scroll_view); 
     h_scroll.setOnTouchListener(scrolling); 

} 

private OnTouchListener scrolling = new OnTouchListener(){ 
    public boolean onTouch(View v, MotionEvent event) { 
     if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == 
     MotionEvent.ACTION_CANCEL){ 
      int scrollX = h_scroll.getScrollX(); 
      int itemWidth = h_scroll.getMeasuredWidth(); 
      int activePage = ((scrollX + itemWidth/2)/itemWidth); 
      int scrollTo = activePage * itemWidth; 
      h_scroll.smoothScrollTo(scrollTo, 0); 


      //page control display the active page button 
      Log.v("MyDebug","Active page = "+activePage); 
      for(int i = 0; i < numberOfPages; i++){ 
       Button aPage = (Button) findViewById(i); 
       if(i == activePage){ 
        aPage.setBackgroundResource(thePage); 
       }else{ 
        aPage.setBackgroundResource(otherPage); 
       } 
      } 

      return true; 
     } else { 
      return false; 
     } 
    } 

}; 


//this is the onClick handler for the page buttons and moves the scroller to the page 
associated with the button. That is through the button ID, which matches the page 
number (0 based of course 

public void selectPage(View v) { 
    int newPage = v.getId(); 
    int itemWidth = h_scroll.getMeasuredWidth(); 
    int scrollTo = newPage * itemWidth; 
    h_scroll.smoothScrollTo(scrollTo, 0); 

    //page control display 
    Log.v("MyDebug","Active page = "+newPage); 
    for(int i = 0; i < numberOfPages; i++){ 
     Button aPage = (Button) findViewById(i); 
     if(i == newPage){ 
      aPage.setBackgroundResource(thePage); 
     }else{ 
      aPage.setBackgroundResource(otherPage); 
     } 
    } 
    } 

    public void finishActivity(View v){ 
     //perform back action 
     finish(); 
    } 

    public void nextActivity(View v){ 
     //move to next activity 
    } 
} 

Это было мое решение. Я уверен, что есть много умных программистов, чем я, поэтому я уверен, что кто-то может это улучшить. В любом случае THANKS stackoverflow !!!!

+2

Hello. Спасибо за этот контент. Однако вы должны предложить свое решение в качестве ответа на свой вопрос, как указано здесь: http://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/ –

+0

Amokrane, Извините, как мне это изменить? –

+0

Брайан, просто оставьте вопрос/проблему в качестве вопроса и переместите решение в качестве ответа. –

ответ

0

Я думаю, что библиотека GreenDroid поможет достичь чего-то похожего на UIPageControl iPhone.

Посмотрите их приложение на рынке GDCatalog. Также вы можете извлечь нужные файлы и сделать pagecontrol. Я использовал его в своем приложении, и он отлично работает. Нужно немного оптимизировать, чтобы сделать его более плавным.

https://github.com/cyrilmottier/GreenDroid

Смежные вопросы