Skip to content Skip to sidebar Skip to footer

Different Widgets (views) For Different Screen Orientations?

I'm quite new developing for Android so I have a very basic question. Basically, I have two screen layouts, one for portrait and another for landscape orientation. I use the folder

Solution 1:

Don't name them differently; the widgets for the same function should share the same ID whether it's in portrait or landscape.

If it's a widget that only exists or functions differently in landscape, just check if it's null after findViewById(), and if that returns null, you know you're not in a configuration with a layout that includes that button.


Solution 2:

Just make sure that your button Id in layout-land is same Id in default layout

Update1 :

ok add not null check before using the widget like this

if( btnPortrait !=null ) { 
// do what you want 
}

Solution 3:

I'm not sure by what you mean in the comments by "they're not the same button" but a way of doing what you want with two different resource ids would be as follows...

public class MyActivity extends Activity {

    Button myButton = null;
    TextView myTextView = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        myButton = (Button) findViewById(R.id.portraitButton);
        if (myButton == null)
            myButton = (Button) findViewById(R.id.landscapeButton);
        myTextView = (TextView) findViewById(R.id.portraitText);
        if (myTextView == null)
            myTextView = (TextView) findViewById(R.id.landscapeText);
    }

    // The following method is your OnClickListener
    public void sayHello(View v) {
        switch (v.getId) {
            case R.id.portraitButton :
                // Do something for portrait
                break;
            case R.id.landscapeButton :
                // Do something for landscape
                break;
        }
    }
}

In your layout files you would then assign the OnClickListener using android:onClick as follows...

For portrait...

<Button
    android:id="@+id/portraitButton"
    ...
    android:onClick="sayHello" >
</Button>

For landscape...

<Button
    android:id="@+id/landscapeButton"
    ...
    android:onClick="sayHello" >
</Button>

In this way, the OnClickListener is set by the inflation process when setContentView(...) is called. It then simply comes down to it determining the resource id to decide what action needs to be taken.


Post a Comment for "Different Widgets (views) For Different Screen Orientations?"