Terence Chow
Terence Chow

Reputation: 11153

Change Text on Landscape mode with Java Code and not XML (Android)

I wrote my layout entirely in java code because it was just more convenient. (I had a lot of textViews and using for statements were more convenient).

However, my TextViews require the day of the week and in portrait mode, I would like to cut the day of the week to a short form. For example, I want "Sunday" to show "Sun" for portrait mode, but "Sunday" for landscape mode.

I understand how to do this in XML files, but how do I do it in code?

I.e. sample code:

LinearLayout parent = new LinearLayout(getApplicationContext());
parent.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
TextView example = new TextView;
example.setLayoutParams(mparams);
example.setText("Sunday"); //<--make this "Sun" when in portrait but "Sunday" in landscape
parent.addView(example);

Upvotes: 0

Views: 622

Answers (2)

nandeesh
nandeesh

Reputation: 24820

If your application is getting restarted when it moves to landscape then you can define the strings that need to be expanded in Landscape mode in values-land

And it is never a good idea to use hard coded strings. Even if you are creating layouts programmatically use strings.xml to store strings

Upvotes: 1

Vishesh Chandra
Vishesh Chandra

Reputation: 7071

You can override the onConfigurationChanged() method in your Activity class, and you can set your text, when orientation will change this method will call... Hope it will helpful to you..:)

       @Override
       public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            // Here you can set text **Sun**
        } else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            //Here you can set text **Sunday**
        }

    }

Upvotes: 1

Related Questions