我正在尝试根据屏幕尺寸扩充 View ,以便我可以使用不同的布局
我试过以下方法
double screen_size = 8
if screen_size >= 10 {
layoutInflator =(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = layoutInflator.inflate(R.layout.mylist, parent, false);
}
if screen_size >= 5 && screen_size <=9){
layoutInflator =(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = layoutInflator.inflate(R.layout.mylist2, parent, false);
}
TextView textview1 = (TextView) row.findViewById(R.id.textView1);
我在 Textview
上收到一个错误,说即使正在运行 if
语句,也无法解析 row
如果我改成
double screen_size = 8
if screen_size >= 10 {
layoutInflator =(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = layoutInflator.inflate(R.layout.mylist2, parent, false);
}
if screen_size >= 5 && screen_size <=9){
layoutInflator =(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = layoutInflator.inflate(R.layout.mylist2, parent, false);
}
View row = layoutInflator.inflate(R.layout.mylist, parent, false);
TextView textview1 = (TextView) row.findViewById(R.id.textView1);
它运行良好但总是运行布局 mylist
而不是 mylist2
我哪里出错了
感谢任何帮助
标记
最佳答案
在 if
语句之外声明 row
,如下所示:
double screen_size = 8
View row = null;
if (screen_size >= 10 {
layoutInflator =(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflator.inflate(R.layout.mylist2, parent, false);
}
if (screen_size >= 5 && screen_size <=9){
layoutInflator =(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflator.inflate(R.layout.mylist2, parent, false);
}
TextView textview1 = (TextView) row.findViewById(R.id.textView1);
关于Android 根据 if 语句更改布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30705239/