zoukankan      html  css  js  c++  java
  • Android版本:使用findViewById()用字符串/在一个循环

    我在做一个Android应用程序,其中有一个数百按钮,每一个特定的回调。现在,我想设置,而不必写几百行代码(用于按钮各一个)这一个循环。 我的问题是:如何才能findViewById不具有静态在键入每个按钮的id? 以下是我想要做的:

     for(int i=0; i<some_value; i++) {
      for(int j=0; j<some_other_value; j++) {
      String buttonID = "btn" + i + "-" + j;
      buttons[i][j] = ((Button) findViewById(R.id.buttonID));
      buttons[i][j].setOnClickListener(this);
      }
     }
    

    在此先感谢!
    本文地址 :CodeGo.net/250944/ 

    ------------------------------------------------------------------------------------------------------------------------- 
    1. 您getIdentifier()

    for(int i=0; i<some_value; i++) {
     for(int j=0; j<some_other_value; j++) {
     String buttonID = "btn" + i + "-" + j;
     int resID = getResources().getIdentifier(buttonID, "id", "com.sample.project");
     buttons[i][j] = ((Button) findViewById(resID));
     buttons[i][j].setOnClickListener(this);
     }
    }
    


    2. 一起来看看这些答案: Android和获取id为铸造一个视图作为字符串 ImageButtons的数组,从一个变量赋值R.view.id 
    3. 你可以尝试做一个int []包含所有的按钮的ID,然后遍历是:

    int[] buttonIDs = new int[] {R.id.button1ID, R.id.button2ID, R.id.button3ID, ... }
    for(int i=0; i<buttonIDs.length; i++) {
     Button b = (Button) findViewById(buttonIDs[i]);
     b.setOnClickListener(this);
    }
    


    4. 如果您要访问您可以使用标签。 中的onClick INT I=的Integer.parseInt(v.getTag); 但你不能访问likw这个那个按钮。 简单的编程方式创建按钮 按按钮B=新的Button(本); 
    5. 在java代码中的XML来创建自定义按钮,而如下图所示我

    Button bs_text[]= new Button[some_value];
     for(int z=0;z<some_value;z++)
      {
       try
       {
       bs_text[z] = (Button) new Button(this);
       }
       catch(ArrayIndexOutOfBoundsException e)
       {
        Log.d("ArrayIndexOutOfBoundsException",e.toString());
       }
      }
    


    6. 如果您的顶层视图只有那些按钮的views,子,你可以做

    for (int i = 0 ; i < yourView.getChildCount(); i++) {
     Button b = (Button) yourView.getChildAt(i);
     b.setOnClickListener(xxxx);
    }
    

    如果存在多个视图你需要检查是否选择了一个是你的一个按钮。

    http://codego.net/250944/

  • 相关阅读:
    2012年的结束
    学习嵌入式的点滴(一)
    面试的点滴(一)
    学习嵌入式的点滴(二)
    DB2 SQL脚本批量执行(转)
    联邦数据库的一个例子(转)
    在 DB2 9.7 for Linux, UNIX, and Windows 上运行 Oracle 应用程序(转)
    WINDOWS批处理命令详解(转)
    SQL1159 Initialization error with DB2 .NET Data Provider, reason code 2;reason code 10
    Oracle Package中的包变量的使用(转)
  • 原文地址:https://www.cnblogs.com/cmblogs/p/4379119.html
Copyright © 2011-2022 走看看