有没有办法从 XML View 中获取参数,修改其中的一些内容,然后将其用作内容 View ?
假设我有一个普通的 LinearLayout,我想让它工作:
LinearLayout layout = (LinearLayout) findViewById(R.layout.main);
setContentView(layout);
代替:
setContentView(R.layout.main);
最佳答案
是的。
更具体地说,我们需要您提供更具体的信息。
编辑
例如,您可以执行以下操作。 假设您的 xml 规范中有一个 TextView:
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="@+id/mytv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="22sp"
android:textStyle="bold"/>
</RelativeLayout>
现在您想以编程方式将 TextView 水平居中:
setContentView(R.id.main);
TextView myTV = (TextView) findViewById(R.id.mytv);
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) myTV.getLayoutParams();
lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
myTV.setLayoutParams(lp);
你只需要在开始时设置contentview,更改变量时不需要重新设置。
关于android - 以编程方式更改 xml 创建的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7428610/