Android change layout depending on if statement

1.6k views Asked by At

Im trying to inflate a view depending on screen size so I can use different layouts

I have tried the following

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

I get an error on the Textview saying row cannot be resolved even tho the if statement is being run

If I change to

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

it runs fine but always runs layout mylist instead of mylist2

Any ideas where im going wrong

Any help appreciated

Mark

3

There are 3 answers

1
Pankaj On BEST ANSWER

Your not casting it to View :

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

Change the line to above line wherever your inflating views.

2
reidzeibel On

Declare the row outside of the if statement, like this :

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);
3
King of Masses On

Declare the View globally and check. it will work

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