简体   繁体   中英

Buttons in android : Visible, Invisible, Gone

I am working on android app and need to define custom buttons.

Initially, I am setting the button to Invisible.

I want to execute a particular method, and check for a String value. If it returns null value, then the button should be still invisible. If it returns some string value, I want to invoke the button and perform some task then.

This is what I tried, but failing.

My app is crashing when the code value returns Null, with error: "attempt to invoke virtual method"

 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();
    }
}

try the code below

 if (code != null && !code.equels("")
        {
            startbtn.setVisibility(View.VISIBLE);
        }
        else
        {
            startbtn.setVisibility(View.GONE);
        }
        startbtn.setOnClickListener(new View.OnClickListener() {
            //Required action
        }

You can set a button in three ways in android: 1. VISIBLE 2. INVISIBLE 3. GONE

Use button.INVISIBLE to hide button instead of button.GONE as latter one removes button from view instead of hiding. This is the reason you are getting null pointer exception.

You may try the below code:

    if (code == null || code.equals("")
    {
        startbtn.setVisibility(View.INVISIBLE);
    }
    else
    {
        startbtn.setVisibility(View.VISIBLE);
    }

If the value in code is null or is empty, we set the button to invisible else it will be visible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM