假设我有一个线性布局,我想在我的程序中,从Java代码中添加一个视图。使用什么方法?我问的不是如何在XML中完成它(我知道XML是如何完成的),而是如何沿着这个示例代码行完成一些事情?
(One View).add(Another View)
就像在Swing中一样。
假设我有一个线性布局,我想在我的程序中,从Java代码中添加一个视图。使用什么方法?我问的不是如何在XML中完成它(我知道XML是如何完成的),而是如何沿着这个示例代码行完成一些事情?
(One View).add(Another View)
就像在Swing中一样。
当前回答
你们也应该确保当你重写onLayout时,你必须调用super。onLayout的所有属性,否则视图将不会被膨胀!
其他回答
要以编程方式添加视图,您可以执行以下操作:
LinearLayout rlmain = new LinearLayout(this);
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.FILL_PARENT);
LinearLayout ll1 = new LinearLayout (this);
ImageView iv = new ImageView(this);
iv.setImageResource(R.drawable.logo);
LinearLayout .LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
iv.setLayoutParams(lp);
ll1.addView(iv);
rlmain.addView(ll1);
setContentView(rlmain, llp);
您还可以添加任意数量的视图。
调用addView是正确的答案,但是要使它工作,还需要做更多的工作。
如果你通过构造函数创建一个视图(例如,Button myButton = new Button();),你需要在新构造的视图上调用setLayoutParams,在你将新构造的子视图添加到父视图之前,传入父视图的LayoutParams内部类的实例。
例如,你可能在你的onCreate()函数中有以下代码,假设你的LinearLayout有id R.id.main:
LinearLayout myLayout = findViewById(R.id.main);
Button myButton = new Button(this);
myButton.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
myLayout.addView(myButton);
确保设置了LayoutParams很重要。每个视图至少需要一个layout_width和一个layout_height参数。获得正确的内部类也很重要。我努力将视图添加到TableRow以正确显示,直到我发现我没有传递TableRow的实例。子视图的setLayoutParams。
你们也应该确保当你重写onLayout时,你必须调用super。onLayout的所有属性,否则视图将不会被膨胀!
我发现最好的方法是使用View的充气静态方法。
View inflatedView = View.inflate(context, yourViewXML, yourLinearLayout);
yourViewXML类似于r。layout。myview
请注意,你需要一个ViewGroup来添加一个视图(这是任何你能想到的布局)
举个例子,假设你有一个片段,它的视图已经膨胀了,你知道根视图是一个布局,你想给它添加一个视图:
View view = getView(); // returns base view of the fragment
if (view == null)
return;
if (!(view instanceof ViewGroup))
return;
ViewGroup viewGroup = (ViewGroup) view;
View popup = View.inflate(viewGroup.getContext(), R.layout.someView, viewGroup);
编辑:
上面例子的Kotlin代码(view是片段的getView())
(view as? ViewGroup)?.let {
View.inflate(context, R.layout.add_credit_card, it)
}
LinearLayout是ViewGroup的子类,它有一个叫做addView的方法。addView方法应该是您想要的。