java - 在 Android 布局调用中使用变量

标签 java android

我想对 Android 应用程序中已有的布局资源进行简单调用,如下所示。我需要做的就是能够使用诸如 myInteger 之类的变量(具有诸如 1,2,3 之类的值)并调用 R.layout.("fragment_main"+myInteger) 而不是调用 R.layout.fragment_main2。为了清楚起见,我需要 Android 将“fragment_main”+myInteger 识别为fragment_main2,以便我可以使用变量

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_main2, container, false);
    TextView textView = (TextView) rootView.findViewById(R.id.section_label);
    textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
    return rootView;
}

最佳答案

recognize "fragment_main"+myInteger as fragment_main2 allowing me to use a variable

使用getIdentifier获取布局ID,布局文件名如下:

int layoutID =getResources().getIdentifier("layout"+ myInteger, 
                             "layout", getActivity().getPackageName()); 

 View rootView = inflater.inflate(layoutID, container, false);

关于java - 在 Android 布局调用中使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33984304/

相关文章:

android - 如何获取当前设备的地区/国家?

Java 二进制搜索

c# - Java 中的双重检查锁定是否需要 `volatile` 而不是 C#?

java子类有方法返回它的类

android - 我想要 TextView 作为可点击的链接

android - 无法在 Android 编辑文本上输入波斯语文本

java - Android 中未找到 WheelView

java - ProgressDialog 在 android 线程中工作

android - 在构建Home()时引发了以下NoSuchMethodError:在null上调用了 '>'方法。接收方:null尝试调用:>(1)

android - 我如何在android中保持状态 'online'