【问题标题】:Android View layoutInflater get Layout by stringAndroid View layoutInflater 通过字符串获取布局
【发布时间】:2021-05-26 03:23:43
【问题描述】:

在 android 上通过使用动态字符串作为 id 来获取带有 layoutInflater 的 View 时遇到问题。

此代码有效:

LayoutInflater layoutInflater = (LayoutInflater) 
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View newView = layoutInflater.inflate(R.layout.my_layout, null);
scrollViewMain.removeAllViews();
scrollViewMain.addView(newView);

但我想通过使用这样的字符串来动态获取视图:

String myString = "my_layout";
LayoutInflater layoutInflater = (LayoutInflater) 
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View newView = layoutInflater.inflate(R.layout.myString, null);
scrollViewMain.removeAllViews();
scrollViewMain.addView(newView);

感谢您帮助理解这一点。

【问题讨论】:

    标签: java android string layout


    【解决方案1】:
    String myString = "my_layout";
    
    int layout_id= context.getResources().getIdentifier(
        myString,
        "layout",
        context.getPackageName()
    );
    
    LayoutInflater layoutInflater = (LayoutInflater) 
    context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View newView = layoutInflater.inflate(layout_id, null);
    scrollViewMain.removeAllViews();
    scrollViewMain.addView(newView);
    

    【讨论】:

    • 不客气,为了让大家搜索相同的问题找到答案,请您标记正确答案吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多