Computer >> 컴퓨터 >  >> 프로그램 작성 >> Android

예를 들어 Android Shared 기본 설정을 설명하는 방법은 무엇입니까?

<시간/>

공유 기본 설정을 사용하여 값을 키 및 값 쌍으로 저장하거나 검색할 수 있습니다. 아래와 같이 5가지 다른 방법을 공유 우선순위에서 사용할 수 있습니다. -

  • 편집() − 공유 환경 설정 값을 수정합니다.

  • 커밋() - xml 파일에서 공유 기본 설정 값을 커밋할 것입니다.

  • 적용() − 편집기에서 공유 환경 설정으로 변경 사항을 다시 커밋합니다.

  • 제거(문자열 키) − 공유 환경 설정 사용 키에서 키와 값을 제거합니다.

  • 넣기() − 공유 환경 설정 xml에 키와 값을 넣을 것입니다.

다음과 같은 공유 기본 설정의 샘플 예제 구문 -

final SharedPreferences sharedPreferences = getSharedPreferences("USER",MODE_PRIVATE);

위의 구문에서 우리는 USER.xml로 공유 기본 설정 파일을 생성했으며 개인 모드는 다른 애플리케이션이 이 공유 기본 설정에 액세스할 수 없음을 의미합니다.

아래 예는 Android에서 공유 기본 설정을 사용하는 방법을 보여줍니다.

1단계 − Android Studio에서 새 프로젝트를 생성하고 파일 ⇒ 새 프로젝트로 이동하여 필요한 모든 세부 정보를 입력하여 새 프로젝트를 생성합니다.

2단계res/layout/activity_main.xml에 다음 코드를 추가합니다. .

<?xml version = "1.0" encoding = "utf-8"?>
<android.support.constraint.ConstraintLayout
   xmlns:android = "https://schemas.android.com/apk/res/android"
   xmlns:app = "https://schemas.android.com/apk/res-auto"
   xmlns:tools = "https://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:layout_height = "match_parent"
   android:orientation = "vertical"
   tools:context = ".MainActivity"
   tools:layout_editor_absoluteY = "81dp">
   <EditText android:id = "@+id/name"
      android:layout_width = "match_parent"
      android:layout_height = "60dp"
      android:layout_marginTop = "8dp"
      android:autofillHints = ""
      android:hint = "NAME" app:layout_constraintTop_toTopOf = "parent"
      tools:layout_editor_absoluteX = "0dp" />
   <EditText android:id = "@+id/address" android:layout_width = "match_parent"
      android:layout_height = "wrap_content"
      android:layout_marginTop = "84dp"
      android:hint = "Phone Number"
      android:importantForAutofill = "no"
      android:inputType = ""
      app:layout_constraintTop_toTopOf = "@+id/name"
      tools:layout_editor_absoluteX = "16dp"
      tools:targetApi = "o" />
   <Button
      android:id = "@+id/button"
      android:layout_width = "108dp"
      android:layout_height = "wrap_content"
      android:layout_marginStart = "8dp"
      android:layout_marginLeft = "8dp"
      android:layout_marginTop = "120dp"
      android:layout_marginEnd = "8dp"
      android:layout_marginRight = "8dp"
      android:gravity = "center_horizontal"
      android:text = "Save"
      app:layout_constraintEnd_toEndOf = "parent"
      app:layout_constraintHorizontal_bias = "0.503"
      app:layout_constraintStart_toStartOf = "parent"
      app:layout_constraintTop_toTopOf = "@+id/address" />
   <Button
      android:id = "@+id/read"
      android:layout_width = "wrap_content"
      android:layout_height = "wrap_content"
      android:layout_marginStart = "8dp"
      android:layout_marginLeft = "8dp"
      android:layout_marginTop = "88dp"
      android:layout_marginEnd = "8dp"
      android:layout_marginRight = "8dp"
      android:gravity = "center_horizontal"
      android:text = "read"
      app:layout_constraintEnd_toEndOf = "parent"
      app:layout_constraintStart_toStartOf = "parent"
      app:layout_constraintTop_toBottomOf = "@+id/button" />
   <TextView
      android:id = "@+id/result"
      android:layout_width = "wrap_content"
      android:layout_height = "0dp"
      android:layout_marginStart = "8dp"
      android:layout_marginLeft = "8dp"
      android:layout_marginTop = "184dp"
      android:layout_marginEnd = "8dp"
      android:layout_marginRight = "8dp"
      android:text = "result"
      app:layout_constraintEnd_toEndOf = "parent"
      app:layout_constraintStart_toStartOf = "parent"
      app:layout_constraintTop_toBottomOf = "@+id/button" />
</android.support.constraint.ConstraintLayout>

위의 xml에는 이름과 주소에 대한 두 개의 편집 텍스트가 포함되어 있습니다. 사용자가 저장 버튼을 클릭하면 값이 공유 기본 설정에 저장되고 사용자가 읽기 버튼을 클릭하면 공유 기본 설정에서 값을 읽게 됩니다.

3단계src/MainActivity.java에 다음 코드를 추가합니다.

package com.example.andy.myapplication;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      final SharedPreferences sharedPreferences = getSharedPreferences("USER",MODE_PRIVATE);
      final EditText name = findViewById(R.id.name);
      final EditText address = findViewById(R.id.address);
      final TextView result = findViewById(R.id.result);
      Button save = findViewById(R.id.button);
      Button read = findViewById(R.id.read);
      read.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            result.setText("Name is "+sharedPreferences.getString("Name","No name")+" Address "+ sharedPreferences.getString("Address","No Address"));
        }
      });
      save.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            if(name.getText().toString().isEmpty() && address.getText().toString().isEmpty()) {
               Toast.makeText(MainActivity.this,"Plz Enter all the data",Toast.LENGTH_LONG).show();
            } else {
               String nameData = name.getText().toString().trim();
               String addressData = address.getText().toString().trim();
               SharedPreferences.Editor editor = sharedPreferences.edit();
               editor.putString("Name",nameData);
               editor.putString("Address",addressData);
               editor.commit();
            }
         }
      });
   }
}

4단계manifest.xml을 변경할 필요가 없습니다. 응용 프로그램을 실행해 보겠습니다. 실제 Android 모바일 장치를 컴퓨터에 연결했다고 가정합니다. Android 스튜디오에서 앱을 실행하려면 프로젝트의 활동 파일 중 하나를 열고 실행 아이콘을 클릭하세요. 예를 들어 Android Shared 기본 설정을 설명하는 방법은 무엇입니까? 도구 모음에서. 모바일 장치를 옵션으로 선택한 다음 기본 화면을 표시할 모바일 장치를 확인하십시오 -

예를 들어 Android Shared 기본 설정을 설명하는 방법은 무엇입니까?

위의 예에서 이름과 주소를 추가하고 저장 버튼을 클릭했습니다.

예를 들어 Android Shared 기본 설정을 설명하는 방법은 무엇입니까?

위의 예에서는 읽기 버튼을 클릭했습니다. 텍스트 보기에 텍스트를 추가합니다.