有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我想对Android应用程序中已有的布局资源做一个简单的调用,如下所示。我所需要做的就是能够使用一个变量,比如myInteger(其值为1,2,3)并调用R.layout。(“fragment_main”+myInteger)而不是调用R.layout。片段2。为了明确起见,我需要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;
}

共 (1) 个答案

  1. # 1 楼答案

    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);