2017-02-22 243 views
0

我無法將項目添加到動態導航抽屜裏,我已經解決了將項目這樣如何添加項目動態點擊導航抽屜

`for(int i = 0; i<lista.size(); i++){ 
      SubMenu menuGroup = menu.addSubMenu(Menu.NONE, i, Menu.NONE, lista.get(i)); 
      for(int j = 0; j<5; j++){ 
       menuGroup.add(item + j); 
      }` 

的部分問題是在這裏:

public boolean onNavigationItemSelected(MenuItem item) { 
    // Handle navigation view item clicks here. 
    int id = item.getItemId(); 

    if (id == R.id.nav_manage) { 
     // Handle the camera action 
     //here comes the action for the first item 

    } else if (id == R.id.item_2) { 
     //here comes the action for item 2 and so on 

所以事情是,一旦我創建的項目動態(已經這樣做了),我怎麼可以添加項的點擊(行動對已經創建的項目)。 我試過for循環,但因爲它的if - else if條件我不能使用for循環。 任何人都可以幫助我嗎?

回答

0

我以前遇到同樣的問題,這些方式

  1. 解決創建一個片段與包和它的佈局
  2. 在MainActivity.java在onNavigationItemSelected
  3. 創建方法
  4. 調用方法

中添加FrameLayout後content_main.xml與ID frag_layout,我做了這些步驟:

FragDetail.java

public class FragDetail extends Fragment { 

@Nullable 
@Override 
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 

    View view = inflater.inflate(R.layout.frag_detail, container, false); 

    Bundle bundle = getArguments(); 

    if(bundle != null) { 

     TextView mText = (TextView) view.findViewById(R.id.txt_detail); 
     mText.setText(bundle.getString("drawer_title")); 
    } 

    return view; 
}} 

frag_detail.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"> 
<TextView 
    android:text="detail clicked" 
    android:layout_width="wrap_content" 
    android:textAppearance="@style/TextAppearance.AppCompat.Headline" 
    android:layout_height="wrap_content" 
    android:layout_centerVertical="true" 
    android:layout_centerHorizontal="true" 
    android:id="@+id/txt_detail" /></RelativeLayout> 

方法MainActivity.java

public FragDetail getFragment(String desc) { 

    FragDetail frag = new FragDetail(); 

    Bundle bundle = new Bundle(); 
    bundle.putString("drawer_title", desc); 

    frag.setArguments(bundle); 

    return frag; 
} 

調用方法

public boolean onNavigationItemSelected(MenuItem item) { 
    // Handle navigation view item clicks here. 

    String nmClient = (String) item.getTitle(); 

    Fragment frag = getFragment(nmClient); 
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); 

    ft.replace(R.id.frag_layout, frag); 
    ft.commit(); 

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
    drawer.closeDrawer(GravityCompat.START); 
    return true; 
} 

我居然發現從這個link

+0

感謝隊友的解決方案,我終於有onNavigationItemSelected做到了,因爲所有的項目做同樣的事情,唯一的區別是名字,因爲我認爲這是不是很難, ,但是你的例子會派上用場,用於另一個項目。 – Alan