세로 및 가로 모드의 두 가지 레이아웃을 만들었습니다. 시나리오는 방향 변경을 기반으로 TextView의 텍스트를 변경하려고합니다. 여기 내 코드는 다음과 같습니다 -setContentview()는 onConfigurationChanged()에서 레이아웃을 변경하지만 안드로이드에서 데이터를 설정하지 않습니다.
의 AndroidManifest.xml :
<activity android:name=".MainActivity"
android:configChanges="orientation|screenSize|keyboardHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
activity_main.xml (세로)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.demo.textdemo.MainActivity">
<TextView
android:id="@+id/textViewHello"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!"
android:layout_gravity="center"
android:gravity="center"
android:textSize="20dp" />
activity_main.xml (가로) :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.demo.textdemo.MainActivity">
<TextView
android:id="@+id/textViewHello"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Hello World!"
android:layout_gravity="center"
android:gravity="center"
android:textSize="20dp"
/>
MainActivity : "안녕하세요"를
public class MainActivity extends AppCompatActivity {
TextView textViewHello;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewHello = (TextView)findViewById(R.id.textViewHello);
Configuration newConfig = getResources().getConfiguration();
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
textViewHello.setText("ORIENTATION LANDSCAPE");
}else {
textViewHello.setText("ORIENTATION PORTRAIT");
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
setContentView(R.layout.activity_main);
textViewHello.setText("ORIENTATION LANDSCAPE");
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
setContentView(R.layout.activity_main);
textViewHello.setText("ORIENTATION PORTRAIT");
}
}
} 처음
, 그것은 텍스트 뷰의 변화는 방향에 따라하지만 난 방향을 변경할 때 보여줍니다 activity_main.xml에서 정의하는 이유는 무엇입니까?
이미 시도했지만 이 설정은 텍스트 만 설정 한 디자인을 변경하지 않고, 가로로 설정된 배경을 빨간색으로 설정하고 세로로는 노랑으로 설정하면 방향 변경시 레이아웃이 변경되지 않는다는 차이점을 알 수 있습니다. –
활동을 프로그래밍 방식으로 작성해야하는 배경을 변경하십시오. – Dhanumjay
방향 변경에 따라 TextView 값을 변경하고 디자인을 변경해야합니다 (배경은 코드를 작성할 때 디자인이 변경되지 않는다는 예입니다) –