正在为菜单项创建新Id



当我使用布局视图创建新菜单项时,默认Id为@+Id/item1。当我选择浏览时,我会得到一个首选项选择器窗口,底部的新"new ID."窗口变灰。我需要做什么来创建一个新的ID?

您可以使用View.generateViewId()。这将为您生成新的id,请确保您保存它,以备需要时让您的应用程序知道它,因为它们没有添加到R.java文件中。

public class ViewUtil {
private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
public static int generateViewId() {
    if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1){
      for (;;) {
          final int result = sNextGeneratedId.get();
          int newValue = result + 1;
          if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
            if (sNextGeneratedId.compareAndSet(result, newValue)) {
                    return result;
                }
        }else{
            return View.generateViewId();
        }
    }
}

最新更新