1. 程式人生 > 程式設計 >Android Studio螢幕方向以及UI介面狀態的儲存程式碼詳解

Android Studio螢幕方向以及UI介面狀態的儲存程式碼詳解

專案:Orientation

package com.example.orientation;
 
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
 
import androidx.appcompat.app.AppCompatActivity;
 
public class MainActivity extends AppCompatActivity {
/*
  = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  本例項主要學習,螢幕翻轉時,介面如何自適應,建立橫屏佈局
  1.禁止切換橫屏:在 AndroidManifest.xml-->application->activity->中設定如下程式碼(android:screenOrientation="portrait")
   <activity android:name=".MainActivity" android:screenOrientation="portrait" >
  2. 建立 Landscape 佈局,橫屏時,會自動載入 Landscape 的佈局介面(清單檔案中,注意去掉 android:screenOrientation="portrait" )
  3. 翻轉螢幕時,儲存視窗控制元件的狀態值;
 
  = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
 */
  Button button;
  TextView textView;
 
  String TAG = "myTag";
 
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
 
    button = findViewById(R.id.button );
    textView = findViewById(R.id.textView);
 
    //如果State中的值不為空,如果有相應的這個元件的值,則讀取出來賦值上去
    if(savedInstanceState !=null)
    {
      String s = savedInstanceState.getString("key");
      textView.setText(s);
    }
 
    button.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        textView.setText(button.getText());
      }
    });
  }
 
  @Override
  protected void onDestroy() {
    super.onDestroy();
    Log.d(TAG,"onDestroy:");
  }
 
  @Override
  //將 textView 中的值,先儲存到 outState 中(鍵值對)
  public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putString("key",textView.getText().toString());
  }
}

擴充套件學習:

UI介面設計

TextView

<TextView
    android:id="@+id/textview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:text="This is a TextView"
    android:textColor="#00ff00"
    android:textSize="24sp" />

要想使得文字居中,需要新增屬性android:gravity="center",可選擇的選項還有top、bottom、left、right、center等,center相當於center_vertical|center_horizontal。

使用android:textSize="24sp"指定文字大小,android:textColor="#00ff00"指定文字顏色。

Button

<Button
    android:id="@+id/button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Button"
    android:textAllCaps="false"/>

在Android中,Button上面的文字預設英文全部大寫,可以通過設定android:textAllCaps="false"改變

EditText

<EditText
    android:id="@+id/edittext"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="HelloWorld"
    android:maxLength="20"
    android:maxLines="1" />

通過設定hint屬性可以得到提示文字,設定maxLines使得輸入框中最大輸入行數。

以上相關知識點如果還有什麼疏漏大家可以直接聯絡小編,感謝你的閱讀和對我們的支援。