【问题标题】:Initializing Widgets in android在android中初始化小部件
【发布时间】:2016-06-26 06:03:08
【问题描述】:

我有 50 个文本视图。我可以避免像这样初始化所有文本视图吗。是否有任何代码可以自动初始化所​​有这些小部件

t1 = (TextView) myFragmentView.findViewById(R.id.tvone);
t2 = (TextView) myFragmentView.findViewById(R.id.tvtwo);
t3 = (TextView) myFragmentView.findViewById(R.id.tvthree);
t4 = (TextView) myFragmentView.findViewById(R.id.tvfour);
t5 = (TextView) myFragmentView.findViewById(R.id.tvfive);
t6 = (TextView) myFragmentView.findViewById(R.id.tvsix);
t50 = (TextView) myFragmentView.findViewById(R.id.tvfifty);

【问题讨论】:

  • 你是说如果我这样使用..我必须强制初始化所有小部件
  • 简而言之,是的,您必须初始化所有这些。

标签: android


【解决方案1】:

您可以通过此方法获取视图中的所有 EditText:

Method to get all EditTexts in a View

您也可以创建一个包含“ID ,Textview”的地图

    HashMap<Integer,EditText> myEditTextList = new HashMap<Integer,EditText>();

    for( int i = 0; i < myLayout.getChildCount(); i++ )
        if( myLayout.getChildAt( i ) instanceof EditText )
            myEditTextList.put(  ((EditText) myLayout.getChildAt( i )).getId() , 
                   ((EditText) myLayout.getChildAt( i )));

【讨论】:

    【解决方案2】:

    您可以通过将所有 TextView 重命名为“tv1 ... tv50”来初始化它们,并使用以下代码:

    int ressourceId;
    int tv_number = 50;
    TextView[] tv = new TextView[tv_number];
    
    for(int i = 0; i < tv_number; i++) {
        ressourceId = getResources().getIdentifier("tv" + (i + 1), "id", context.getPackageName());
        tv[i] = (TextView) myFragmentView.findViewById(ressourceId);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-04
      相关资源
      最近更新 更多