当我在更改微调器时动态尝试更改布局时,我遇到了问题。 我需要从onItemSelectedListener方法中找到主视图。 这里是代码
public class CustomOnItemSelectedListener implements AdapterView.OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (parent.getSelectedItemPosition()==0){//Apertura di un libro
LinearLayout lyt_libro = new LinearLayout(getApplicationContext());
lyt_libro.setOrientation(LinearLayout.VERTICAL);
//HERE THE PROBLEM. HOW CAN I FIND THE MAIN LAYOUT IN WHICH I CAN ADD THE lyt_libro?
final EditText etx_numeroPagine = new EditText(getApplicationContext());
lyt_libro.addView(etx_numeroPagine);
[... other stuff....]
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
ScrollView view_mainScroll = new ScrollView(getApplicationContext());
LinearLayout lyt_main = new LinearLayout(getApplicationContext());
view_mainScroll.addView(lyt_main);
lyt_main.setOrientation(LinearLayout.VERTICAL);
final Spinner spn_selectInterrogationType = new Spinner(getApplicationContext());
lyt_main.addView(spn_selectInterrogationType);
final ArrayAdapter<String> spn_selectInterrItemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
spn_selectInterrItemAdapter.add("Apertura di un libro");
spn_selectInterrItemAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn_selectInterrogationType.setAdapter(spn_selectInterrItemAdapter);
spn_selectInterrogationType.setPrompt("Tipo di metodo utilizzato");
spn_selectInterrogationType.setOnItemSelectedListener(new CustomOnItemSelectedListener());
setContentView(view_mainScroll);
}
我评论了我遇到问题的地方..我该怎么做才能找到它?我对java和android都很新,所以我有点失落:) 我有另一个疑问:使用getApplicationContext()是否正确?根据我对api文档的理解,最好不要使用它,但如果没有它我怎么办呢......
非常感谢!! :d
编辑: 我正在从代码创建所有布局,因为我需要在运行时动态更改每个元素,所以我需要使用函数或类似的东西检索它。使用xml我没有问题,但它们不是我需要的
答案 0 :(得分:0)
您可以在XML中使用标识符作为主布局,在代码中可以使用findViewById(R.id.name_in_your_xmlFile)找到它
还要记住要投射到您正在接收的视图。
答案 1 :(得分:0)
将xml文件中的名称/ ID提供给包含组件的布局。
然后使用findViewById获取布局。
添加您的观点。
另一种技术可能是在您的xml文件中声明您的字段,其中属性可见性已消失,并且在您的代码中,为了响应您的事件,获取视图(通过上面的id)和setVisilibity到View.VISIBLE。
此致 斯特凡