Android 根据 if 语句更改布局

Android change layout depending on if statement

我正在尝试根据屏幕尺寸扩充视图,以便我可以使用不同的布局

我试过以下

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 上收到一个错误,说 row 即使 if 语句正在 运行

也无法解决

如果我换成

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);

您没有将其投射到视图:

row = (View)layoutInflator.inflate(R.layout.mylist2, parent, false);

将膨胀视图所在的行更改为上面的行。

全局声明View并检查。它会起作用

View row =null;

double screen_size = 8

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);