1

我如何打开新活动(在列表视图元素单击时)在右侧/左侧保持相同的抽屉?

4

2 回答 2

1

如果您为新活动指定抽屉布局(在 XML 中)并将相同的导航抽屉代码从原始活动复制到新活动,它应该可以工作。如果您要这样做,我建议将所有常见代码(例如您可能用于填充抽屉内导航列表的任何自定义列表适配器、您的 onItemClickListener() 等)移动到它自己的类中,并让您的两个活动从那里访问常用方法。但是,如果您可以选择使用片段,正如@Matt_9.0 所建议的那样,它将使导航抽屉在以后更易于维护。

于 2013-09-09T20:36:36.677 回答
0

检查 是你想要什么的教程然后也有 bummi 的建议,这里是代码

XML 布局

<!-- 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>

此片段用于包含您想要的不同布局

com.package.appname.layout 包 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;
    }
}

现在创建片段布局并在 MainACtivity.class 中调用它们,例如

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;
    }

}

如果您需要进一步的帮助,请告诉我..

于 2013-12-23T09:02:56.220 回答