如何添加项目动态点击导航抽屉

如何添加项目动态点击导航抽屉

问题描述:

我无法将项目添加到动态导航抽屉里,我已经解决了将项目这样如何添加项目动态点击导航抽屉

`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循环。 任何人都可以帮助我吗?

我以前遇到同样的问题,这些方式

  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