【问题标题】:How to get another widget from the same layout?如何从同一布局中获取另一个小部件?
【发布时间】:2014-07-29 12:14:46
【问题描述】:

我的代码如下。我只是不想为我的 EditText 和 findViewById 设置一个 ID。因为我正在构建动态用户界面。所以静态id对我来说没用。我现在正试图从 linearLayout 中获取 EditText,但它还没有工作。有什么想法吗?

LinearLayout linearLayout = new LinearLayout(this);
LayoutParams cbLayoutParams = new LayoutParams(
                            LayoutParams.WRAP_CONTENT,
                            LayoutParams.WRAP_CONTENT);
                    locationLayout.setLayoutParams(cbLayoutParams);
                    locationLayout.setOrientation(LinearLayout.VERTICAL);

EditText edtText = new EditText(this);
edtText.setEnable(false);
edtText.setLayoutParams(new LayoutParams(150,50));
linearLayout.addView(edtText);

Button button = new Button(this);
button.setText("say hello");
button.setOnClickListener(new OnClickListener(){
     @Override
     public void onClick(View v){
         EditText edt = null;
         for(int i=0; i<linearLayout.getChildCount();i++){
            Class<?> c = (Class<?>) linearLayout.getChildAt(i).getClass();
            if(c.getName().equals("android.widget.EditText")){
                edt = (EditText) linearLayout.getChildAt(i);
            }
         }
         edt.setText("hello");
     }
});

【问题讨论】:

  • 呵呵,没用。我一开始就这么试过。如果这么简单,我不会浪费时间发布问题。

标签: android android-layout android-widget


【解决方案1】:

您需要将您的EditText 设为最终版本。

final EditText edtText = new EditText(this);

然后您可以在按钮的onClick 中使用最终的edtText 引用:

LinearLayout linearLayout = new LinearLayout(this);
LayoutParams cbLayoutParams = new LayoutParams(
                            LayoutParams.WRAP_CONTENT,
                            LayoutParams.WRAP_CONTENT);
                    locationLayout.setLayoutParams(cbLayoutParams);
                    locationLayout.setOrientation(LinearLayout.VERTICAL);

final EditText edtText = new EditText(this);
edtText.setEnabled(false);
edtText.setLayoutParams(new LayoutParams(150,50));
linearLayout.addView(edtText);

Button button = new Button(this);
button.setText("say hello");
button.setOnClickListener(new OnClickListener(){
     @Override
     public void onClick(View v){
         edtText.setText("hello");
     }
});

【讨论】:

  • 测试一下,看看是否一切正常:)
  • 我的问题真的是我无法为那个 edtText 设置标签。当我做 edtText.setTag("hello").它说 IllegalArgumentException: The key must be an application-specific resource id。 :3
  • 我想你想setText而不是setTag:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-01
相关资源
最近更新 更多