Deepti Maduskar
Deepti Maduskar

Reputation: 69

choosing between two layouts for the same class in android?

I am trying to choose between two different layouts based on a value of a certain parameter and set that layout for my class.Both the layouts are having the same ids of all the views.If we dynamically allocate ids to the views of the two layout wont there be a ambiguity?When i tried practically I am getting a null pointer exception.Is this null pointer because of this ambiguity only??Can anybody please help.

Upvotes: 1

Views: 361

Answers (3)

Deniz
Deniz

Reputation: 12530

if(condition) {
       setContentView(R.layout.activity_main); 
    } else {
       setContentView(R.layout.activity_main_2); 
    }

When you set different views, it may cause null pointer exception when any of the view is missing between this layouts.

So you should make sure that your findViewById returns not null. OR just add check when you try to use this views in the code.

Advanced....

Anyway if you already know all these things and have enough experience with all these stuffs, Try the belw listed libraries it will help you a lot

  1. https://github.com/JakeWharton/butterknife
  2. https://github.com/roboguice/roboguice

You can avoid "repetitive, cumbersome boilerplate coding parts. Indeed, we should focus on logic, not on meta programming".

These will help you to avoid all these findViewById...stuffs and you can slim your code...less bugs!

Upvotes: 0

Ahmed Hegazy
Ahmed Hegazy

Reputation: 12605

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // condition can be from getIntent() or from SharedPreferences or whatever 
    if(condition) {
       setContentView(R.layout.activity_main); 
    } else {
       setContentView(R.layout.activity_main_2); 
    }

    // If they have the same components, but different layouts only
    // You can use it as usual with findViewById(R.id.view_id);
    Button btnExample = findViewById(R.id.btn_example);
}

Upvotes: 1

Tin Megali
Tin Megali

Reputation: 801

I could't understand well what you asked. If i'm correct you asking if you can use the same id for a view on different layouts. Yes you can. Unless you try to inflate those two layouts at the same time. Then you will have a problem.

You need to narrow you error.

Upvotes: 0

Related Questions