2015年4月1日 星期三

Android Studio在NavigationDrawer新增Fragment的方法

一開始用AS創一個NavigationDrawerActivity
其實已經可以直接用來跑基本的功能了

如果要做到能夠選1,2,3Fragment,然後切畫面到那邊
可以參考這個影片
https://www.youtube.com/watch?v=zwqzhY5i2rc

不過他用的是
android.app.Fragment;
現在新的版本大致上
android.support.v4.app.Fragment

兩者區別可以參考這篇
http://blog.csdn.net/duguang77/article/details/17580993

目前版本1.1.0直接開內建都是用v4 library



1.大致上就是新增二個 Fragment.java

import android.support.v4.app.Fragment;   //這裡以v4方法做

public class menu1_fragment extends Fragment {
    View rootview;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootview = inflater.inflate(R.layout.menu1_fragment, container, false);
        return rootview;
    }
}

2.再創二個xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:gravity="center_horizontal">


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="1"
        android:id="@+id/textView" />

</RelativeLayout>


3.然後在mainActivity裡找到方法onNavigationDrawerItemSelected
並在裡面寫進swich,接著在replace最後的參數改成objFragment這個新物件

   public void onNavigationDrawerItemSelected(int position) {
        Fragment objFragment = null;

        switch (position) {
            case 0:
                objFragment = new menu1_fragment();
                break;
            case 1:
                objFragment = new menu2_fragment();
                break;


        }
        // update the main content by replacing fragments
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.container, objFragment)
                .commit();
    }

已經可以基本換Fragment了

2015年3月31日 星期二

Android用inflater切換畫面的方法

http://fgchen.blogspot.tw/2012/11/android-1.html?view=flipcard

用法1

http://fgchen.blogspot.tw/2012/11/android-2.html?view=flipcard

用法2