在Android布局调用中使用变量

时间:2015-11-29 15:12:49

标签: 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;
}

1 个答案:

答案 0 :(得分:2)

  

将“fragment_main”+ myInteger识别为fragment_main2,允许我这样做   使用变量

使用int layoutID =getResources().getIdentifier("layout"+ myInteger, "layout", getActivity().getPackageName()); View rootView = inflater.inflate(layoutID, container, false); 使用布局文件名获取布局ID:

<?php
function clearArray($arr) {
    if(is_array($arr)) {
        foreach($arr as $element) {
            $cont=trim($element); //make sure to have cr/lf parts removed (difference between line seperator)
            if(!empty($cont)) {
                $newArray[]=$cont;
            }
        }
        return $newArray;
    }
    return false;
}
$content='<div class="first">
  <div class="second">
     Some content inside second div
    <div class="third">
      Some more content inside third div
    </div>
  </div>
</div>';
$strippedContent=strip_tags($content);
$content=explode("\n", $strippedContent);
$content=clearArray($content);
print_r($content);