android 中使用 number picker ( 使用资源文件strings.xml )

访问量: 270

1. 在xml 中:  (注意, 这两个都是隐藏状态, ) 

    <NumberPicker
        android:id="@+id/the_language_picker"
        android:layout_width="match_parent"
        android:layout_height="180dp"
        android:visibility="gone"
        />
    <Button
        android:id="@+id/the_language_picker_ok_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="OK"
        android:visibility="gone"
        />

2. 在java中: (分别设置了点击事件,)

        // 根据resource 资源显示文字
        languagePicker = (NumberPicker) findViewById(R.id.the_language_picker);
        String english = getResources().getString(R.string.english);
        String chinese = getResources().getString(R.string.chinese);
        String khmer = getResources().getString(R.string.khmer);

        // 初始化这个 number picker
        String[] data = new String[]{english, chinese, khmer};
        languagePicker.setMinValue(0);
        languagePicker.setMaxValue(data.length-1);
        languagePicker.setDisplayedValues(data);

        // 设置 ok 按钮,让它做一些相应.
        ok = (Button) findViewById(R.id.the_language_picker_ok_button);
        ok.setOnClickListener(new View.OnClickListener(){
            public void onClick(View view){

                // get language string
                Integer languageInteger = languagePicker.getValue();
                String languageString = "en";
                if(languageInteger == 0){
                    languageString = "en";
                }else if(languageInteger == 1){
                    languageString = "zh";
                }else if(languageInteger == 2){
                    languageString = "km";
                }

                // set language
                SharedPreferences settings = getSharedPreferences(Constants.REFERENCE_NAME, 0);
                SharedPreferences.Editor editor = settings.edit();
                editor.putString("language", languageString);
                editor.commit();
                Log.d("== doSwitchLanguage", " MyApplication changed language to: " + languageString);

                // hide ui,不隐藏其实也行
                languagePicker.setVisibility(View.GONE);
                ok.setVisibility(View.GONE);

                // 重新启动当前的activity 
                Intent intent = new Intent(MainActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            }
        });

订阅/RSS Feed

Subscribe

分类/category