2014-10-06 92 views
0

所以我用一個簡單navigation drawerAndroid,我怎麼能改變onClick函數?

public static class PlanetFragment extends Fragment { 
public static final String ARG_PLANET_NUMBER = "planet_number"; 

public PlanetFragment() { 
    // Empty constructor required for fragment subclasses 
} 
private View RootView; 
@Override 
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, 
         Bundle savedInstanceState) { 




    int i = getArguments().getInt(ARG_PLANET_NUMBER); 
    RootView = inflater.inflate(R.layout.home_fragment, container, false); 


    if(i == 0) 
    { 
     RootView = inflater.inflate(R.layout.home_fragment, container, false); 
     ImageButton login = (ImageButton)RootView.findViewById(R.id.imageButton); 
     login.setOnClickListener(new View.OnClickListener() { 
      @Override 

      public void onClick(View v) { 
       RootView = inflater.inflate(R.layout.login_fragment, container, false); 
      } 
     }); 
    } 
    if(i == 1) 
    { 
     RootView = inflater.inflate(R.layout.login_fragment, container, false); 
    } 
    if(i == 3) 
    { 
     RootView = inflater.inflate(R.layout.login_fragment, container, false); 
    } 

    return RootView; 
} 

}

所以,只需如果我點擊第一個元素在我的導航 - 這是工作,比我看到屏幕按鈕。如果我想點擊這個按鈕,我需要改變意圖。

所以這個代碼必須做到:

public void onClick(View v) { 
    RootView = inflater.inflate(R.layout.login_fragment, container, false); 
} 

但它不工作。我究竟做錯了什麼?

+0

使用以小寫字符開頭的變量名稱是一種很好的做法。例如'rootView'而不是'RootView'。 – Simas 2014-10-06 14:50:07

+1

這不是正確的做法。無論何時您需要打開新的活動 - Android建議使用Intents。 [官方教程在這裏](http://developer.android.com/training/basics/firstapp/starting-activity.html)應該可以幫到你。 – 2014-10-06 14:50:09

+0

但如果我將使用活動,我不能使用側邊欄。是? – 2014-10-06 14:51:25

回答

1

您不瞭解Fragments。你的句子:

RootView = inflater.inflate(R.layout.login_fragment, container, false); 

這只是創建一個通用的觀點,但是這是不一樣的一個Fragment。什麼,你需要做的就是創建一個新的Fragment類,然後改變你的OnClick方法是這樣的:

public void onClick(View v) { 
    FragmentTransaction myTransaction = getFragmentManager().beginTransaction(); 
    myTransaction.replace(R.id.your_fragment_container, new YourNewFragment()); 
    myTransaction.commit(); 
} 

這將取代您要顯示一個當前Fragment

+0

但在這裏'myTransaction.replace(R.id.your_fragment_container,new YourNewFragment());' 我的片段容器是當前的xml佈局? – 2014-10-06 15:13:17

+0

是的。 「Fragment」運行在「Activity」之上,以及添加到堆棧中的任何其他「Fragment」。所以在你的MainActivity xml中,你需要添加一個容器,在你的'片段'將被添加的地方。其他方面,'活動'不知道在哪裏放置'片段'。查看[documentation](http://developer.android.com/training/basics/fragments/fragment-ui.html)以獲取更多指導 – 2014-10-06 15:20:32

+0

謝謝你對我的工作! – 2014-10-06 15:22:56