2

如何在运行时在android中动态定位编辑文本?

以下是我的代码:

public class ABCActivity extends Activity   {
  EditText ed;

  @Override
  public void onCreate(Bundle savedInstanceState) 
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ed = new EditText(ABCActivity.this);
    ed.setEnabled(false);    
    layout =new LinearLayout(this);  
    LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT, 1.0f);            
    layout.setLayoutParams(params);
    btn = new Button(this); 
    btn.setLayoutParams(params);
    btn.setText("Change");

    RelativeLayout.LayoutParams params2 = (RelativeLayout.LayoutParams) ed.getLayoutParams();
    params2.leftMargin = 10;
    params2.topMargin = 10;
    ed.setLayoutParams(params2);

    layout.addView(btn);   
    layout.addView(ed);

   }    
}

给力关闭:

RelativeLayout.LayoutParams params2 = (RelativeLayout.LayoutParams) ed.getLayoutParams();

错误:空指针异常我尝试使用相对布局.....但不起作用

4

2 回答 2

1

Lars Vogel在这里有一个很棒的教程。基本上,您必须使用特定于您的布局的 LayoutParams 来通过 Java 定位视图。

于 2012-07-03T13:36:22.147 回答
1

你可以EditText这样设置你的位置,我给它10、10的虚拟值。

         RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) ed.getLayoutParams();
         params.leftMargin = 10;
         params.topMargin = 10;
         ed.setLayoutParams(params);
于 2012-07-03T13:47:15.433 回答