Android更改布局取决于if语句

时间:2015-06-08 09:13:52

标签: android if-statement views layout-inflater

我试图根据屏幕尺寸对视图进行充气,以便我可以使用不同的布局

我尝试了以下

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

我出错的任何想法

任何帮助表示赞赏

标记

3 个答案:

答案 0 :(得分:2)

row语句之外声明if,如下所示:

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

答案 1 :(得分:1)

你没有把它投到视图:

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

在您的充气视图的任何位置将线条更改为上一行。

答案 2 :(得分:0)

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

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