android 中的按钮:可见、不可见、消失

我正在开发 Android 应用程序,需要定义自定义按钮。


最初,我将按钮设置为不可见。


我想执行一个特定的方法,并检查字符串值。如果它返回空值,那么该按钮应该仍然不可见。如果它返回一些字符串值,我想调用按钮并执行一些任务。


这就是我尝试过的,但失败了。


当代码值返回 Null 时,我的应用程序崩溃,并出现错误:“尝试调用虚拟方法”


 public String code = "";

 Button startbtn;

 @Override

 protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_retrieve_visits);


    startbtn = findViewById(R.id.videobutton);

    startbtn.setOnClickListener(new View.OnClickListener() {

        @Override

        public void onClick(View v) {

            //code

        }

    });

//more code here

}


public void parseData(String response)

{

 try {

        JSONObject json = new JSONObject(response);

        JSONArray data = json.getJSONArray("data");

        for (int i = 0; i < data.length(); i++) 

        {

            JSONObject child = data.getJSONObject(i);

            code = child.getString("code");

        }


        if(data.length()==0) ////check for empty array

            startbtn.setVisibility(View.INVISIBLE);


        else

            startbtn.setVisibility(View.VISIBLE);

    }

    catch (Exception e) {

        e.printStackTrace();

    }

}


海绵宝宝撒
浏览 114回答 3
3回答

神不在的星期二

尝试下面的代码&nbsp;if (code != null && !code.equels("")&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; startbtn.setVisibility(View.VISIBLE);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; startbtn.setVisibility(View.GONE);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; startbtn.setOnClickListener(new View.OnClickListener() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //Required action&nbsp; &nbsp; &nbsp; &nbsp; }

长风秋雁

在android中你可以通过三种方式设置按钮:1.VISIBLE 2.INVISIBLE 3.GONE使用button.INVISIBLE隐藏按钮而不是因为button.GONE后一个按钮从视图中删除而不是隐藏。这就是您收到空指针异常的原因。

慕田峪7331174

您可以尝试以下代码:&nbsp; &nbsp; if (code == null || code.equals("")&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; startbtn.setVisibility(View.INVISIBLE);&nbsp; &nbsp; }&nbsp; &nbsp; else&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; startbtn.setVisibility(View.VISIBLE);&nbsp; &nbsp; }如果代码中的值为 null 或为空,我们将按钮设置为不可见,否则它将可见。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java