Android 根据 if 语句更改布局

标签 android if-statement view layout-inflater

我正在尝试根据屏幕尺寸扩充 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/

相关文章:

c++ - 浮点值不显示准确的位数 C++

php - 包含 .phtml zend

java - 如何在 "X"no 之后显示插页式广告应用程序中的点击次数?

android - 在内部存储中保存公共(public)文件

android - 透明主题将项目置于中心

python - 我可以在 Python 中收到始终评估为 true 的警告吗?

if-statement - 如何在 CASE in Progress 4GL 中编写此 IF 语句?

android - 可靠获取状态栏高度解决KitKat半透明导航问题

ios - 为整个 UISplitViewController 添加背景

android - 如何实现这种布局