Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/229.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在Android应用程序中更改运行时主题_Java_Android_Android Layout_Themes - Fatal编程技术网

Java 在Android应用程序中更改运行时主题

Java 在Android应用程序中更改运行时主题,java,android,android-layout,themes,Java,Android,Android Layout,Themes,我是android编程新手,我正在尝试在我的手电筒应用程序上应用一个主题。错误似乎是当我尝试应用两个主题之一时单击“确定”按钮 以下是我在SimpleNotificationAppActivity.java上的代码 public class SimpleNotificationAppActivity extends Activity implements android.content.DialogInterface.OnClickListener{ private boolean is

我是android编程新手,我正在尝试在我的手电筒应用程序上应用一个主题。错误似乎是当我尝试应用两个主题之一时单击“确定”按钮

以下是我在SimpleNotificationAppActivity.java上的代码

public class SimpleNotificationAppActivity extends Activity implements android.content.DialogInterface.OnClickListener{
    private boolean isFlashOn = false;
    private Camera camera;
    //private ImageButton button;
    private Button button;
    private MediaPlayer button2;

    ////////////
    public final static int CREATE_DIALOG  = -1;
    public final static int THEME_HOLO_LIGHT  = 0;
    public final static int THEME_HOLO  = 1;

    int position;
    ///////////////

    @Override
    protected void onStop() {
        super.onStop();

        if (camera != null) {
            camera.release();
        }
    }




    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        //setTheme(android.R.style.Theme_Holo_Light);
        setContentView(R.layout.main);
        button = (Button) findViewById(R.id.buttonFlashlight);
        button2 = MediaPlayer.create(SimpleNotificationAppActivity.this,R.raw.two_tone_nav); //SOM DO CLIQUE
        //button = (ImageButton) findViewById(R.drawable.image_on);
        //button.setBackgroundResource(R.drawable.switch_on);
        Context context = this;
        PackageManager pm = context.getPackageManager();


        if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            Log.e("err", "Device has no camera.");
            Toast.makeText(getApplicationContext(),
                    "Sorry, your device doesn't have camera :(",
                    Toast.LENGTH_SHORT).show();

            return;
        }

        camera = Camera.open();
        final Parameters p = camera.getParameters();

        button.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                if (isFlashOn) {
                    Log.i("info", "torch is turned off!");      
                    button2.start();
                    p.setFlashMode(Parameters.FLASH_MODE_OFF);
                    camera.setParameters(p);                    
                    isFlashOn = false;
                    //button.setText("Torch-ON");
                    button.setBackgroundResource(R.drawable.button_on);
                } else {
                    Log.i("info", "torch is turned on!");
                    button2.start();
                    p.setFlashMode(Parameters.FLASH_MODE_TORCH);
                    camera.setParameters(p);                    
                    isFlashOn = true;
                    //button.setText("Torch-OFF");
                    button.setBackgroundResource(R.drawable.button_off);
                }
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main_activity_actions, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        super.onOptionsItemSelected(item);
        switch(item.getItemId()){
        case R.id.theme:
            themeMenuItem();
            break;
        case R.id.about:
            aboutMenuItem();
            break;
        }
        return true;

        }
    private void aboutMenuItem(){
        new AlertDialog.Builder(this)
        .setTitle("About")
        .setMessage("Flashlight app developed and designed by Rui Moreira.\n\nfacebook.com/RuiSousaMoreira")
        .setNeutralButton("Ok", new DialogInterface.OnClickListener() {


            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub

            }
        })
        .setIcon(R.drawable.app_icon_small)
        .show();
    }

    private void themeMenuItem(){

        //setTheme(android.R.style.Theme_Holo);
        //setTheme(R.layout.main2);
////////////////////////////////////////////////////
position = getIntent().getIntExtra("position", -1);

switch(position)
{
case CREATE_DIALOG:
createDialog();
break;
case THEME_HOLO_LIGHT:
setTheme(android.R.style.Theme_Holo_Light);
break;
case THEME_HOLO:
setTheme(android.R.style.Theme_Holo_Light_DarkActionBar);
break;
default:
}

//super.onCreate(savedInstanceState);
//setContentView(R.layout.main);


////////////////////////////////////////////////////


    }


    private void createDialog()
    {
        /** Options for user to select*/
        String choose[] = {"Holo Light","Holo Dark"};

        AlertDialog.Builder b = new AlertDialog.Builder(this);

        /** Setting a title for the window */
        b.setTitle("Choose your Application Theme");

        /** Setting items to the alert dialog */
        b.setSingleChoiceItems(choose, 0, null);

        /** Setting a positive button and its listener */
        b.setPositiveButton("OK", this);//
        /*TRIED THIS TOO, BUT DOESNT SOLVES THE PROBLEM
         * 
         * b.setPositiveButton("Ok", new DialogInterface.OnClickListener() {


            public void onClick(DialogInterface dialog, int which) {
            ///TESTE

                AlertDialog alert = (AlertDialog)dialog;
                int position = alert.getListView().getCheckedItemPosition();

                finish();
                Intent intent = new Intent();
                intent.putExtra("position", position);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);

                ///TESTE

            }
        });*/

        /** Setting a positive button and its listener */
        b.setNegativeButton("Cancel", null);

        /** Creating the alert dialog window using the builder class */
        AlertDialog d = b.create();

        /** show dialog*/
        d.show();
    }


    public void onClick(DialogInterface dialog, int which) {
        // TODO Auto-generated method stub
        AlertDialog alert = (AlertDialog)dialog;
        int position = alert.getListView().getCheckedItemPosition();

        finish();
        Intent intent = new Intent(this, SimpleNotificationAppActivity.class);
        intent.putExtra("position", position);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);

    }
基本上,当我点击这里的“主题”时:

此对话框将显示:

我选择主题,并想按ok更新应用程序的主题。 谁能帮我实现这个目标?我很欣赏你的建议:)正如你所尝试的,这是改变主题的方法。但是,

请注意,应在中实例化任何视图之前调用此函数 上下文(例如在调用setContentView(View)或 充气(内部,视图组))


因此,您必须重新启动应用程序。我的解决方案,可能是肮脏的,是杀死
活动
,调用应用程序的主要活动,并在
意图
中提供一些关于必须应用什么主题的信息。

就像小孩子说的那样,简单地使用
setTheme()
是不起作用的。它应该在
设置内容视图(视图)
之前使用。您需要做的是按一下“确定”按钮重新启动应用程序,然后在应用程序重新启动时,通过setTheme()设置新主题(在setContentView(视图)之前执行此操作)

要在一秒钟后重新启动应用程序,可以使用此选项(根据应用程序替换活动):

下面是我在评论中提到的示例代码:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedPreferences shared=getSharedPreferences("app_name", Activity.MODE_PRIVATE);
        String theme=shared.getString("theme", null);
        if(theme != null && theme.equals("LIGHT")){
            setTheme(R.style.Theme_light);
        }else{
            setTheme(R.style.Theme_dark);
        }
            setContentView(R.layout.activity_main);
}

发布错误报告/logcat请重新启动应用程序,新主题才能生效,并在
super()之前应用新主题。onCreate()
Eclipse不会显示任何错误,因为我可以运行应用程序。当我运行它并按“OK”时,会发生这种情况[link()@ruimorera请使用
imgur
上传imagesTry,谢谢你的建议。我有点理解这个想法,但我不知道如何在onCreate()中设置主题。
public void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setTheme(???);setContentView(R.layout.main);…..
我做不到setTheme(android.R.style.Theme\u Holo\u Light\u DarkActionBar)因为应用程序总是以暗主题启动,而不是在您的情况下选择的主题,您可以将主题保存在SharedReferences中,该主题由用户选择,并在“OK”按钮的onclick方法中使用该重新启动代码。然后在onCreate()中方法,从SharedReferences获取保存的主题,并将其设置为setTheme()。我将通过添加该部分来更新答案。
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedPreferences shared=getSharedPreferences("app_name", Activity.MODE_PRIVATE);
        String theme=shared.getString("theme", null);
        if(theme != null && theme.equals("LIGHT")){
            setTheme(R.style.Theme_light);
        }else{
            setTheme(R.style.Theme_dark);
        }
            setContentView(R.layout.activity_main);
}