【问题标题】:Android creating button programmatically issueAndroid以编程方式创建按钮问题
【发布时间】:2011-10-26 12:21:15
【问题描述】:

我正在尝试在我的 android 应用程序上以编程方式创建按钮,具体取决于我的 sqlite 数据库中有多少项目。按钮在那里,但我的问题是在每个按钮上设置onClick,因为我想在用户单击按钮时显示不同的内容。我现在正在使用此代码:

   for(cursorCol.move(0); cursorCol.moveToNext(); cursorCol.isAfterLast()){
          Id = Integer.parseInt(cursorCol.getString(cursorCol.getColumnIndex("id")));
          Log.i("Id","Id : "+Id);
                titleButton = cursorCol.getString(cursorCol.getColumnIndex("title"));
             Log.i("titleButton","titleButton : " + titleButton);
             elemOrder1 = Integer.parseInt(cursorCol.getString(cursorCol.getColumnIndex("elemOrder")));
               Log.i("elemOrder1 ","elemOrder1 : " + elemOrder1 );    

               btn = new Button(this); 
                  btn.setText("  " + titleButton + "  "); 
                  btn.setId(Id);
                  btn.setTextColor(Color.parseColor("#000000"));
                  btn.setTextSize(12);
                  btn.setPadding(10, 10, 10, 10);
                  btn.setBackgroundResource(R.drawable.gray_button);
                  btnlayout.addView(btn,params); 

                  btn.setOnClickListener(new View.OnClickListener() {

          @Override
          public void onClick(View v) {
           infoCard.removeAllViews();

           for(int i=0;i<=cursorCol.getCount();i++){

            Log.i("","titleButton : "+titleButton);

               }
          }
}

但问题是,当我单击按钮时,它只显示最后一个titleButton。其实我不需要显示titleButton,我只是为了测试目的。任何想法如何为每个按钮创建不同的 onClick 方法?

【问题讨论】:

    标签: android button


    【解决方案1】:

    我认为问题出在这行代码上:

    btn = new Button(this);
    

    您在循环中一遍又一遍地编辑同一个按钮,而不是实际创建一个新按钮。要创建一个新的,您需要这样做:

    Button new_btn = new Button(this);
    

    这将在您每次迭代 for 循环时创建一个全新的。

    【讨论】:

    • 这是正确的答案!非常感谢!我没有意识到我每次都在使用同一个按钮。
    • 没问题。我很乐意提供帮助。
    • 他确实用“new”创建了一个新实例,所以这不是问题。
    • 他正在创建一个新实例并覆盖他正在使用的旧实例。他只有一个按钮,“btn”。此外,他在上面评论说我的解决方案有效,所以我认为这是问题所在。
    • 也许我已经累了,但我仍然不明白“btn”是如何导致问题的:在每个循环中,都会创建一个新实例,将其存储在一个字段中(I giess),并且这个新实例被配置并添加到视图中。因此,它是存储在字段中还是本地都无关紧要。 (在代码 sn-p 中,他不会在 for 循环之外访问 btn)。对我来说,“titleButton”字段看起来很可疑,因为它实际上是在 for 循环之外使用的(在 OnClick 方法中),所以我的猜测是点击了正确的按钮,但显示了错误的消息。
    猜你喜欢
    • 2014-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多