-1

I have app designed for tablet and now I want to make layout for phone, but my phone layout has different views and at some points different functionality and I'm facing such problem: layout-sw600dp/layout_a.xml(for tablet) has 2 buttons and layout-sw320dp/layout_a.xml(for phone) has just one now in code I set two listeners and app crashes with null pointer exception because second button is missing from layout. Any suggestions how can I implement different functionality for these screens?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
LeTadas
  • 3,436
  • 9
  • 33
  • 65

3 Answers3

1

Set a boolean flag (eg isUsingTabletLayout) and when you load the tablet layout wrap the binding of the views and the setting of the listeners inside that boolean check. If it's false the code will skip the views that are not present in the phone

Nikos Hidalgo
  • 3,666
  • 9
  • 25
  • 39
0

First step :. Know which layout is loaded, you can do it using below mention way

Link : How can I detect which layout is selected by Android in my application?

Step two :

By knowing which layout s loaded , you can enable codes for button.

If ( layout == tablayout ){ Load button 1, and button 2. }else { load button 1 only. }

Hope, this will work.

Thank you.

vivekonline
  • 1
  • 1
  • 3
-1

Use getIdentifier() method. If it returns a non zero value, the resource exists, otherwise it doesn't exist.

String button_id="your_button_id";
//where button id is defined as android:id="@+id/your_button_id"

String resource_type= "id";

getResources().getIdentifier(button_id, resource_type, getApplicationContext().getPackageName());
touhid udoy
  • 4,005
  • 2
  • 18
  • 31