iT邦幫忙

0

[Android Studio] -- Day 2 主題變換Theme01

前言

剛好讀到layout的部分,來做之前都沒試過的APP色系轉換。


正文

這次利用spinner來切換layout

layout畫面

https://ithelp.ithome.com.tw/upload/images/20210129/20134772LvR0i4bR4P.pnghttps://ithelp.ithome.com.tw/upload/images/20210129/20134772dnAxOsjkCI.png

code

  • onCreate
    Spinner spinner;
    String[] color = {"null","origin","dark"};
    //null是用來判斷Toast的,可以刪除

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        spinner=findViewById(R.id.spinner);
        ArrayAdapter<String> colorList = new ArrayAdapter<>(MainActivity.this,
                android.R.layout.simple_spinner_dropdown_item,
                color);
        spinner.setAdapter(colorList);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this, "您選擇了:" + color[position], Toast.LENGTH_SHORT).show();
                if(color[position]=="dark"){
                    layout2();
                }
                if(color[position]=="origin"){
                    layout1();
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
    }
  • layout1
    跟上面是一樣的,layout切換時要重啟spinner的功能
private void layout1() {
        setContentView(R.layout.activity_main); //換layout
        
        spinner=findViewById(R.id.spinner);
        ArrayAdapter<String> colorList = new ArrayAdapter<>(MainActivity.this,
                android.R.layout.simple_spinner_dropdown_item,
                color);
        spinner.setAdapter(colorList);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this, "您選擇了:" + color[position], Toast.LENGTH_SHORT).show();
                if(color[position]=="dark"){
                    layout2();
                }
                if(color[position]=="origin"){
                    layout1();
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });

    }
  • layout2
    同layout1,只是要記得換成layout2的名稱
    setContentView(R.layout.activity_main2);
    spinner=findViewById(R.id.spinner2);

結語

存檔很重要QAQ。
存檔很重要QAQ。
存檔很重要QAQ。
這次走的是陽春版的,layout寫死的。有機會可以試試看在.java裡面直接修正color.xml的資訊。


尚未有邦友留言

立即登入留言