开发者

Android Portrait vs Landscape

开发者 https://www.devze.com 2023-04-02 08:52 出处:网络
I know that it is possible to ha开发者_高级运维ve a layout for both portrait and landscape mode (that\'s not the problem). Say in portrait mode I want to display 3 textviews (actually I have 3 distinc

I know that it is possible to ha开发者_高级运维ve a layout for both portrait and landscape mode (that's not the problem). Say in portrait mode I want to display 3 textviews (actually I have 3 distinct graphs, one for each axis xyz) and in landscape I only want one textview (in my case one graph that contains all 3 axis), all of there view got their own id.

Now in the corresponding activity, how do you setup the ui controls? Because in landscape mode there's only one textview whereas in portrait mode I got 3. So when I'm in portrait mode I'm only able to write something in textview 1 2 and 3 but nothing into landscape's textview and vice versa.

Manually checking if the ui control is here (not null) can't be the right solution, right?

e.g

Say in portrait mode I have a textview with id 'text1' and in landscape one with 'text2'. Now in the activity's on create method I do the following:

text1 = (TextView) findViewById(R.id.text1);
text2 = (TextView) findViewById(R.id.text2);

text1.setText("some text");
text2.setText("some other text");

I'll always get a NullPointerException because in either case one of the textviews does not exist. It would be possible to check if the field is not null before using it, but that would introduce more logic to take care of - so it gets less maintainable


You can create in both layouts and hide them with visibility="gone" to keep a valid reference to the view


Because you may not want to waste resources setting and processing fields that are not visible in your layout, unless this makes sense in your app, you should check for null Views and this would give you and idea of which orientation you are processing:

text1 = (TextView) findViewById(R.id.text1);
text2 = (TextView) findViewById(R.id.text2);

if ( text1 != null ) text1.setText("some text");
if ( text2 != null ) text2.setText("some other text");


Maybe by make some textviews visible/invisible depending on which mode you're using? You could detect which mode you're using by : getResources().getConfiguration().orientation

I don't know if that really answer to your question but..

Best,

0

精彩评论

暂无评论...
验证码 换一张
取 消