如何在运行时动态定位编辑文本?
followig是我的代码:
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();
错误:空指针异常 我尝试使用相对布局..... 但是不起作用
答案 0 :(得分:1)
Lars Vogel here有一个很好的教程。基本上,您必须使用特定于布局的LayoutParams来通过Java定位视图。
答案 1 :(得分:1)
你可以通过这种方式设置EditText
的位置,我给它的值为10,10。
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) ed.getLayoutParams();
params.leftMargin = 10;
params.topMargin = 10;
ed.setLayoutParams(params);