根据android studio中的位置动态调整线性布局
问题描述:
我使用android studio开发应用程序,我想要一个包含取决于位置而变化的选项列表的表格,例如,如果我在纽约市我想显示3个选项,但如果我在圣地亚哥,我想要5.我的想法是有一个线性布局,它具有wrap_content作为其中每个选项的其他线性布局的高度。问题是我不知道如何修改(添加/删除)内部布局,或者是否有更好的方法来实现这个想法。用户也可以选择其中一个选项,它们是可点击的。根据android studio中的位置动态调整线性布局
下面是一些例子
答
这里是我尝试添加线性布局动态的代码,它工作:)。首先加载要在其中动态创建线性布局的父布局。然后,您必须决定要显示的布局数量,并将其传递给代码中的'NumberOfLayouts'变量,以便动态创建线性布局。
/*Loading the Parent Layout*/
LinearLayout ParentLayout = (LinearLayout)findViewById(R.id.ParentLayout);
/*Dynamically creating your linear layouts*/
for(int i=0; i<NumberOfLayouts; i++){
LinearLayout linearLayout = new LinearLayout(getApplication());
TextView textView = new TextView(this);
textView.setText("Sample Text");
linearLayout.addView(textView);
ParentLayout.addView(linearLayout);
/*Adding listener for the individual layouts*/
linearLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Your code or method to be executed while clicking the dynamically created linear layout
}
});
}
答
// first, find the container view by using findViewById;
LinearLayout root = (LinearLayout) findViewById(R.id.container);
// then inflate the child view by using an inflater
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View childView = inflater.inflate(R.layout.childView, null);
// finally, add the child view to the container
root.addView(childView);