如何从相同的布局中获取另一个小部件?

时间:2014-07-29 12:14:47

标签: android android-layout android-widget

我的代码如下。我只是不想为我的EditText和findViewById设置一个id。因为我正在构建动态ui。所以静态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");
     }
});

1 个答案:

答案 0 :(得分:1)

您需要进行EditText决赛。

final EditText edtText = new EditText(this);

然后您可以使用最终的edtText引用内部按钮的onClick

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");
     }
});