在安卓中,我应该在哪里初始化我的切换小部件?

huangapple go评论77阅读模式
英文:

Where should I initialize my switch widget Android

问题

我在我的应用程序中有一个选项菜单,在其中我有一个选项,它打开一个包含一些小部件的对话框。我无法弄清楚在哪里初始化我的小部件,以便它不会产生空指针异常。

我应该在哪里放置 Switch sw = findViewById(R.id.switch1),以便在对话框打开之前可以使用 sw.setChecked(<在代码中确定的条件>)

MainActivity.java:

package com.example
//导入语句
public class MainActivity extends Activity 
{ 
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main, menu);
		return true;
	}
    @Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
	
		switch (item.getItemId())
		{
			case R.id.option:
                // sw.setChecked(true); // 这里的代码会导致问题
				Dialog dialog = new Dialog(this);
				dialog.setContentView(R.layout.dialog);
				dialog.show();
			
			default:
			    return false;
		}
	}
}

在OnCreate()中调用sw.setChecked()时的错误日志:

09-04 16:38:48.358 2395 2395 E     AndroidRuntime                               FATAL EXCEPTION: main
09-04 16:38:48.358 2395 2395 E     AndroidRuntime                               Process: com.PjMathematician.ImgMath, PID: 2395
09-04 16:38:48.358 2395 2395 E     AndroidRuntime                               java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.PjMathematician.ImgMath/com.PjMathematician.ImgMath.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method &#39;android.view.View android.view.Window.findViewById(int)&#39; on a null object reference
...

当我注释掉 sw.setChecked(true) 语句时,此错误消失。

英文:

I have an options menu in my app, and in that I have an option which opens a dialog box which has some widgets. I am not being able to figure out where should I initialize my widgets so that it doesnt give a null pointer exception.

Where should I put Switch sw = findViewById(R.id.switch1) so that i can use sw.setChecked(&lt;condition gets decided in the code&gt;) before the dialog box opens.

MainActivity.java:

package com.example
//imports
public class MainActivity extends Activity 
{ 
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main, menu);
		return true;
	}
    @Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
	
		switch (item.getItemId())
		{
			case R.id.option:
                sw.setChecked(true);
				Dialog dialog = new Dialog(this);
				dialog.setContentView(R.layout.dialog);
				dialog.show();
			
			default:
			    return false;
		}
	}

		

Error log when i call sw.setChecked inside OnCreate()

-04 16:38:48.358 2395 2395 E     AndroidRuntime                               FATAL EXCEPTION: main
09-04 16:38:48.358 2395 2395 E     AndroidRuntime                               Process: com.PjMathematician.ImgMath, PID: 2395
09-04 16:38:48.358 2395 2395 E     AndroidRuntime                               java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.PjMathematician.ImgMath/com.PjMathematician.ImgMath.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method &#39;android.view.View android.view.Window.findViewById(int)&#39; on a null object reference
09-04 16:38:48.358 2395 2395 E     AndroidRuntime                               at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2855)
09-04 16:38:48.358 2395 2395 E     AndroidRuntime                               at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3093)
09-04 16:38:48.358 2395 2395 E     AndroidRuntime                               at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
09-04 16:38:48.358 2395 2395 E     AndroidRuntime                               at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
09-04 16:38:48.358 2395 2395 E     AndroidRuntime                               at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
09-04 16:38:48.358 2395 2395 E     AndroidRuntime                               at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1816)
09-04 16:38:48.358 2395 2395 E     AndroidRuntime                               at android.os.Handler.dispatchMessage(Handler.java:106)
09-04 16:38:48.358 2395 2395 E     AndroidRuntime                               at android.os.Looper.loop(Looper.java:193)
09-04 16:38:48.358 2395 2395 E     AndroidRuntime                               at android.app.ActivityThread.main(ActivityThread.java:6865)
09-04 16:38:48.358 2395 2395 E     AndroidRuntime                               at java.lang.reflect.Method.invoke(Native Method)
09-04 16:38:48.358 2395 2395 E     AndroidRuntime                               at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:504)
09-04 16:38:48.358 2395 2395 E     AndroidRuntime                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
09-04 16:38:48.358 2395 2395 E     AndroidRuntime                               Caused by: java.lang.NullPointerException: Attempt to invoke virtual method &#39;android.view.View android.view.Window.findViewById(int)&#39; on a null object reference
09-04 16:38:48.358 2395 2395 E     AndroidRuntime                               at android.app.Activity.findViewById(Activity.java:4125)
09-04 16:38:48.358 2395 2395 E     AndroidRuntime                               at com.PjMathematician.ImgMath.MainActivity.&lt;init&gt;(MainActivity.java:307)
09-04 16:38:48.358 2395 2395 E     AndroidRuntime                               at java.lang.Class.newInstance(Native Method)
09-04 16:38:48.358 2395 2395 E     AndroidRuntime                               at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:69)
09-04 16:38:48.358 2395 2395 E     AndroidRuntime                               at android.app.Instrumentation.newActivity(Instrumentation.java:1231)
09-04 16:38:48.358 2395 2395 E     AndroidRuntime                               at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2842)
09-04 16:38:48.358 2395 2395 E     AndroidRuntime                               ... 11 more

This error disappears when I comment out the sw.setChecked(true) statement

答案1

得分: 0

主活动

package com.example;
//导入语句
public class MainActivity extends Activity 
{ 
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //在这里初始化开关
        Switch sw = findViewById(R.id.switch1);
        if(sharedPreferenceObj == 你的逻辑){
          //在这里放置你的业务逻辑
        }else{
          //如果条件为假,则在这里执行操作
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {

        switch (item.getItemId())
        {
            case R.id.option:
                sw.setChecked(true);
                Dialog dialog = new Dialog(this);
                dialog.setContentView(R.layout.dialog);
                dialog.show();

            default:
                return false;
        }
    }
}
英文:

You should do this.

Main Activity

 package com.example
//imports
public class MainActivity extends Activity 
{ 
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //initialize the switch here
        Switch sw = findViewById(R.id.switch1);
        if(sharedPreferenceObj == your logic){
          //your business logic here
        }else{
          //if condition is false then do stuff here
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
    
        switch (item.getItemId())
        {
            case R.id.option:
                sw.setChecked(true);
                Dialog dialog = new Dialog(this);
                dialog.setContentView(R.layout.dialog);
                dialog.show();
            
            default:
                return false;
        }
    }

答案2

得分: 0

我认为这会起作用因为Switch视图位于对话框内您应该使用dialog.findViewById(R.id.switch1)来获取其实例
```java
package com.example
//导入
public class MainActivity extends Activity 
{ 
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
    
        switch (item.getItemId())
        {
            case R.id.option:
                sw.setChecked(true);
                Dialog dialog = new Dialog(this);
                dialog.setContentView(R.layout.dialog);
                Switch sw = dialog.findViewById(R.id.switch1);
                sw.setChecked(condition);
                dialog.show();
            
            default:
                return false;
        }
    }
英文:

I think this will work, since the Switch view is inside the dialog box, you should get its instance using dialog.findViewById(R.id.switch1);

package com.example
//imports
public class MainActivity extends Activity 
{ 
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
    
        switch (item.getItemId())
        {
            case R.id.option:
                sw.setChecked(true);
                Dialog dialog = new Dialog(this);
                dialog.setContentView(R.layout.dialog);
                Switch sw = dialog.findViewById(R.id.switch1);
                sw.setChecked(condition);
                dialog.show();
            
            default:
                return false;
        }
    }

huangapple
  • 本文由 发表于 2020年9月4日 19:48:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/63740607.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定