1

오른쪽/왼쪽에 동일한 서랍을 유지하면서 새로운 활동 (listview 요소 클릭)을 어떻게 열 수 있습니까?동일한 서랍을 오른쪽/왼쪽으로 유지하면서 새 활동을 열려면 어떻게해야합니까?

+0

PS 목록보기는 서랍의 한 요소입니다. – Storm

+0

[Fragments] (http://developer.android.com/guide/components/fragments.html)가 좋은 옵션이라고 생각합니다. –

+0

파편이 없어도 될까요? 만약 당신이 giude 또는 somethings 다른 사람을 알고 계시다면 – Storm

답변

1

새로운 활동 (XML에서)에 대한 서랍 레이아웃을 지정하고 원래 활동의 동일한 탐색 서랍 코드를 새 활동으로 복사하면 작동해야합니다. 이 작업을 수행하려면 모든 공통 코드 (예 : 서랍 안의 탐색 목록, onItemClickListener() 등)를 자체 클래스로 채우고 두 개의 코드를 사용하기 위해 사용할 수있는 사용자 지정 목록 어댑터 활동은 거기에서 일반적인 방법에 접근합니다. 그러나 @ Matt_9.0이 제안한 바와 같이 조각을 사용할 수있는 옵션이있는 경우 길 아래에서 탐색 서랍을 더 잘 관리 할 수 ​​있습니다.

0

확인 This 이 유 bummi의 제안도 그런 을 원하는에 대한 튜토리얼입니다, 여기에 코드입니다

이 조각은 다른를 포함하는 데 사용됩니다

<!-- This holds our menu --> 

<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" > 

    <ListView 
     android:id="@+id/activity_main_menu_listview" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:background="@drawable/menu" 
     android:cacheColorHint="#00000000" > 
    </ListView> 
</LinearLayout> 

<FrameLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/activity_main_content_fragment" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:background="@color/White" > 

</FrameLayout> 

XML 레이아웃 당신이 원하는 어느 쪽이든 레이아웃

c 패키지 MainLayout.class가

public class MainLayout extends LinearLayout { 

    // Duration of sliding animation, in miliseconds 
    private static final int SLIDING_DURATION = 500; 
    // Query Scroller every 16 miliseconds 
    private static final int QUERY_INTERVAL = 16; 

    // MainLayout width 
    int mainLayoutWidth; 

    // Sliding menu 
    private View menu; 

    // Main content 
    private View content; 
    private View subContent = findViewById(R.id.activity_main_content_fragment); 
    // menu does not occupy some right space 
    // This should be updated correctly later in onMeasure 
    private static int menuRightMargin = 150; 

    // The state of menu 
    private enum MenuState { 
     HIDING, 
     HIDDEN, 
     SHOWING, 
     SHOWN, 
    }; 

    // content will be layouted based on this X offset 
    // Normally, contentXOffset = menu.getLayoutParams().width = this.getWidth - menuRightMargin 
    private int contentXOffset; 

    // menu is hidden initially 
    private MenuState currentMenuState = MenuState.HIDDEN; 

    // Scroller is used to facilitate animation 
    private Scroller menuScroller = new Scroller(this.getContext(), 
      new EaseInInterpolator()); 

    // Used to query Scroller about scrolling position 
    // Note: The 3rd paramter to startScroll is the distance 
    private Runnable menuRunnable = new MenuRunnable(); 
    private Handler menuHandler = new Handler(); 

    // Previous touch position 
    int prevX = 0; 

    // Is user dragging the content 
    boolean isDragging = false; 

    // Used to facilitate ACTION_UP 
    int lastDiffX = 0; 

    // Constructor 

    // 3 parameters constructor seems to be unavailable in 2.3 
    /* 
    public MainLayout(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
    } 
    */ 

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

    public MainLayout(Context context) { 
     super(context); 
    } 

    // Overriding LinearLayout core methods 

    // Ask all children to measure themselves and compute the measurement of this 
    // layout based on the children 
    @Override 
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
     super.onMeasure(widthMeasureSpec, heightMeasureSpec); 

     mainLayoutWidth = MeasureSpec.getSize(widthMeasureSpec); 
     menuRightMargin = mainLayoutWidth * 10/100; 
     // Nothing to do, since we only care about how to layout 
    } 

    // This is called when MainLayout is attached to window 
    // At this point it has a Surface and will start drawing. 
    // Note that this function is guaranteed to be called before onDraw 

    @Override 
    protected void onAttachedToWindow() { 
     super.onAttachedToWindow(); 

     // Get our 2 child View 
     menu = this.getChildAt(0); 
     content = this.getChildAt(1); 
     content.setOnTouchListener(new OnTouchListener() { 
      @Override 
      public boolean onTouch(View v, MotionEvent event) { 
       return MainLayout.this.onContentTouch(v, event); 
      } 
     }); 

     // Initially hide the menu 
     menu.setVisibility(View.GONE); 
    } 

    // Called from layout when this view should assign a size and position to each of its children 
    @Override 
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 
     //Log.d("MainLayout.java onLayout()", "left " + left + " top " + top + " right " + right + " bottom " + bottom); 
     //Log.d("MainLayout.java onLayout()", "getHeight " + this.getHeight() + " getWidth " + this.getWidth()); 

     // True if MainLayout 's size and position has changed 
     // If true, calculate child views size 
     if(changed) { 
      // Note: LayoutParams are used by views to tell their parents how they want to be laid out 

      //Log.d("MainLayout.java onLayout()", "changed " + changed); 

      // content View occupies the full height and width 
      LayoutParams contentLayoutParams = (LayoutParams)content.getLayoutParams(); 
      contentLayoutParams.height = this.getHeight(); 
      contentLayoutParams.width = this.getWidth(); 

      // menu View occupies the full height, but certain width 
      LayoutParams menuLayoutParams = (LayoutParams)menu.getLayoutParams(); 
      menuLayoutParams.height = this.getHeight(); 
      menuLayoutParams.width = this.getWidth() - menuRightMargin;   
     } 

     // Layout the child views  
     menu.layout(left, top, right - menuRightMargin, bottom); 
     content.layout(left + contentXOffset, top, right + contentXOffset, bottom); 

    } 

    // Custom methods for MainLayout 

    // Used to show/hide menu accordingly 
    public void toggleMenu() { 
     // Do nothing if sliding is in progress 
     if(currentMenuState == MenuState.HIDING || currentMenuState == MenuState.SHOWING) 
      return; 

     switch(currentMenuState) { 
     case HIDDEN: 
      currentMenuState = MenuState.SHOWING; 
      menu.setVisibility(View.VISIBLE); 
      menuScroller.startScroll(0, 0, menu.getLayoutParams().width, 
        0, SLIDING_DURATION); 
      break; 
     case SHOWN: 
      currentMenuState = MenuState.HIDING; 
      menuScroller.startScroll(contentXOffset, 0, -contentXOffset, 
        0, SLIDING_DURATION); 
      break; 
     default: 
      break; 
     } 

     // Begin querying 
     menuHandler.postDelayed(menuRunnable, QUERY_INTERVAL); 

     // Invalite this whole MainLayout, causing onLayout() to be called 
     this.invalidate(); 
    } 

    // Query Scroller 
    protected class MenuRunnable implements Runnable { 
     @Override 
     public void run() { 
      boolean isScrolling = menuScroller.computeScrollOffset(); 
      adjustContentPosition(isScrolling); 
     } 
    } 

    // Adjust content View position to match sliding animation 
    private void adjustContentPosition(boolean isScrolling) { 
     int scrollerXOffset = menuScroller.getCurrX(); 

     //Log.d("MainLayout.java adjustContentPosition()", "scrollerOffset " + scrollerOffset); 

     // Translate content View accordingly 
     content.offsetLeftAndRight(scrollerXOffset - contentXOffset); 

     contentXOffset = scrollerXOffset; 

     // Invalite this whole MainLayout, causing onLayout() to be called 
     this.invalidate(); 

     // Check if animation is in progress 
     if (isScrolling) 
      menuHandler.postDelayed(menuRunnable, QUERY_INTERVAL); 
     else 
      this.onMenuSlidingComplete(); 
    } 

    // Called when sliding is complete 
    private void onMenuSlidingComplete() { 
     switch (currentMenuState) { 
     case SHOWING: 
      currentMenuState = MenuState.SHOWN; 
      break; 
     case HIDING: 
      currentMenuState = MenuState.HIDDEN; 
      menu.setVisibility(View.GONE); 
      break; 
     default: 
      return; 
     } 
    } 

    // Make scrolling more natural. Move more quickly at the end 
    // See the formula here http://cyrilmottier.com/2012/05/22/the-making-of-prixing-fly-in-app-menu-part-1/ 
    protected class EaseInInterpolator implements Interpolator { 
     @Override 
     public float getInterpolation(float t) { 
      return (float)Math.pow(t-1, 5) + 1; 
     } 

    } 

    // Is menu completely shown 
    public boolean isMenuShown() { 
     return currentMenuState == MenuState.SHOWN; 
    } 

    // Handle touch event on content View 
    public boolean onContentTouch(View v, MotionEvent event) { 
     // Do nothing if sliding is in progress 
     if(currentMenuState == MenuState.HIDING || currentMenuState == MenuState.SHOWING) 
      return false; 

     // getRawX returns X touch point corresponding to screen 
     // getX sometimes returns screen X, sometimes returns content View X 
     int curX = (int)event.getRawX(); 
     int diffX = 0; 

     switch(event.getAction()) { 
     case MotionEvent.ACTION_DOWN: 
      //Log.d("MainLayout.java onContentTouch()", "Down x " + curX); 
      prevX = curX; 
      return true; 

     case MotionEvent.ACTION_MOVE: 
      //Log.d("MainLayout.java onContentTouch()", "Move x " + curX); 

      // Set menu to Visible when user start dragging the content View 
      if(!isDragging) { 
       isDragging = true; 
       menu.setVisibility(View.VISIBLE); 
      } 

      // How far we have moved since the last position 
      diffX = curX - prevX; 

      // Prevent user from dragging beyond border 
      if(contentXOffset + diffX <= 0) { 
       // Don't allow dragging beyond left border 
       // Use diffX will make content cross the border, so only translate by -contentXOffset 
       diffX = -contentXOffset; 
      } else if(contentXOffset + diffX > mainLayoutWidth - menuRightMargin) { 
       // Don't allow dragging beyond menu width 
       diffX = mainLayoutWidth - menuRightMargin - contentXOffset; 
      } 

      // Translate content View accordingly 
      content.offsetLeftAndRight(diffX); 

      contentXOffset += diffX; 

      // Invalite this whole MainLayout, causing onLayout() to be called 
      this.invalidate(); 

      prevX = curX; 
      lastDiffX = diffX; 
      return true; 

     case MotionEvent.ACTION_UP: 
      //Log.d("MainLayout.java onContentTouch()", "Up x " + curX); 

      Log.d("MainLayout.java onContentTouch()", "Up lastDiffX " + lastDiffX); 

      // Start scrolling 
      // Remember that when content has a chance to cross left border, lastDiffX is set to 0 
      if(lastDiffX > 0) { 
       // User wants to show menu 
       currentMenuState = MenuState.SHOWING; 

       // No need to set to Visible, because we have set to Visible in ACTION_MOVE 
       //menu.setVisibility(View.VISIBLE); 

       //Log.d("MainLayout.java onContentTouch()", "Up contentXOffset " + contentXOffset); 

       // Start scrolling from contentXOffset 
       menuScroller.startScroll(contentXOffset, 0, menu.getLayoutParams().width - contentXOffset, 
         0, SLIDING_DURATION); 
      } else if(lastDiffX < 0) { 
       // User wants to hide menu 
       currentMenuState = MenuState.HIDING; 
       menuScroller.startScroll(contentXOffset, 0, -contentXOffset, 
         0, SLIDING_DURATION); 
      } 

      // Begin querying 
      menuHandler.postDelayed(menuRunnable, QUERY_INTERVAL); 

      // Invalite this whole MainLayout, causing onLayout() to be called 
      this.invalidate(); 

      // Done dragging 
      isDragging = false; 
      prevX = 0; 
      lastDiffX = 0; 
      return true; 

     default: 
      break; 
     } 

     return false; 
    } 
} 

지금 조각 레이아웃을 만들고 더 알려 도움을 원하는 경우

public class HomeActivity extends FragmentActivity { 
    ImageButton ibMenu; 
    View view; 
    MotionEvent events; 
    boolean doubleBackToExitPressedOnce=false; 
    ImageButton iv,ivabout_content; 
    MainLayout mainLayout; 
    // ListView menu 
    private ListView lvMenu; 
    private String[] lvMenuItems; 
    TextView tvTitle; 
    public View.OnTouchListener gestureListener; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     mainLayout = (MainLayout) this.getLayoutInflater().inflate(R.layout.activity_home, null); 
     setContentView(mainLayout); 

     // Init menu 
     lvMenuItems = getResources().getStringArray(R.array.menu_items); 
     lvMenu = (ListView) findViewById(R.id.activity_main_menu_listview); 
     ArrayAdapter<String> menuAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, lvMenuItems); 
     lvMenu.setAdapter(menuAdapter); 
     iv = (ImageButton) findViewById(R.id.ibHomeLatestEvent); 
     ivabout_content = (ImageButton) findViewById(R.id.ibAboutLearn); 
     lvMenu.setOnItemClickListener(new OnItemClickListener(){ 

      @Override 
      public void onItemClick(AdapterView<?> parent, View view, int position, 
        long id) { 
       // TODO Auto-generated method stub 
       onMenuItemClick(parent,view,position,id); 
      } 

     }); 
     ibMenu = (ImageButton) findViewById(R.id.activity_main_content_button_menu); 
     ibMenu.setOnClickListener(new OnClickListener(){ 

      @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 
       toggleMenu(v); 
      } 

     }); 
     tvTitle = (TextView) findViewById(R.id.activity_main_content_title); 
     FragmentManager fm = HomeActivity.this.getSupportFragmentManager(); 
     FragmentTransaction ft = fm.beginTransaction(); 

     Fragment fragment = new Fragment(); 
     ft.add(R.id.activity_main_content_fragment, fragment); 
     ft.commit(); 
     gestureListener = new View.OnTouchListener() { 

      @Override 
      public boolean onTouch(View v, MotionEvent event) { 
       // TODO Auto-generated method stub 
         return mainLayout.onContentTouch(v, event); 
      } 
     }; 
     iv.setOnTouchListener(gestureListener);  

    } 

    public void toggleMenu(View v) { 
     // TODO Auto-generated method stub 
     mainLayout.toggleMenu(); 
    } 

    protected void onMenuItemClick(AdapterView<?> parent, View view, 
      int position, long id) { 
     // TODO Auto-generated method stub 
     String selectedItem = lvMenuItems[position]; 
     String currentItem = tvTitle.getText().toString(); 

     // Do nothing if selectedItem is currentItem 
     if(selectedItem.compareTo(currentItem)==0){ 
      mainLayout.toggleMenu(); 
      return; 
     } 
    FragmentManager fm = HomeActivity.this.getSupportFragmentManager(); 
    FragmentTransaction ft = fm.beginTransaction(); 
    Fragment fragment = null; 


    if(selectedItem.compareTo("Home") == 0) { 
     fragment = new FragmentHome(); 
    } else if(selectedItem.compareTo("About") == 0) { 
     fragment = new FragmentAbout(); 
    } else if(selectedItem.compareTo("What's new") == 0) { 
     fragment = new Fragmentnew(); 
    } else if(selectedItem.compareTo("Things to do") == 0) { 
     fragment = new FragmentThingsToDo(); 
    } else if(selectedItem.compareTo("Holiday in Lavasa") == 0) { 
     fragment = new FragmentHolidayInLavasa(); 
    } else if(selectedItem.compareTo("Offers") == 0) { 
     fragment = new FragmentOffers(); 
    } else if(selectedItem.compareTo("Getting to Lavasa") == 0) { 
     fragment = new FragmentGettingLavasa(); 
    } else if(selectedItem.compareTo("Map") == 0){ 
     fragment = new FragmentMap(); 
    } else if(selectedItem.compareTo("Downloads") == 0) { 
     fragment = new FragmentDownloads(); 
    } else if(selectedItem.compareTo("Help Desk") == 0) { 

    } 
     if(fragment != null) { 
      // Replace current fragment by this new one 
      ft.replace(R.id.activity_main_content_fragment, fragment).addToBackStack("tag").commit(); 
      // Set title accordingly 
      tvTitle.setText(selectedItem); 
     } 

     // Hide menu anyway 
     mainLayout.toggleMenu(); 
    } 

    @Override 
    public void onBackPressed() { 
     if (mainLayout.isMenuShown()) { 
      mainLayout.toggleMenu(); 
     } 
     else if (doubleBackToExitPressedOnce) { 
      super.onBackPressed(); 
      return; 
     } 
     this.doubleBackToExitPressedOnce = true; 
     Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show(); 
     new Handler().postDelayed(new Runnable() { 

      @Override 
      public void run() { 
      doubleBackToExitPressedOnce=false; 

      } 
     }, 2000); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.home, menu); 
     return true; 
    } 

} 

처럼 MainACtivity.class 에서 그들에게 전화 om.package.appname.layout ..

+1

Ohk 나는 업데이트 된 답변을 확인했다. –