使按钮可见和不可见

时间:2014-05-24 22:09:31

标签: android button android-edittext show-hide

所以我的问题是以下我做了2个功能,目标是返回一个edittext有没有写的东西,如果它有我希望它使一个按钮可见,如果不是我希望buton保持隐形。但这不是我的所有代码

功能,这是我所做的功能:

private boolean checkEditText(EditText edit) {
return edit.getText().length() == 0;
}



 void updateButtonState() {
if(checkEditText(inputdtestab) && checkEditText(quantidade))
{
inputdtestab.setError("yipikaei");
quantidade.setError("mudfukkerrr");
}
else{
     // Create button
Button btnCreateProduct = (Button) findViewById(R.id.button2);
btnCreateProduct.setVisibility(View.visible);

    }
 } 

这不工作,我认为原因是因为它没有运行代码的else部分,因为我尝试创建一个按钮,当我点击它使按钮出现,它工作正常。但按我的意愿行事,它不起作用。

所有代码:

 @SuppressLint({ "NewApi", "CutPasteId" })
public class Newlin_ProductActivity extends Activity{

 /** WebServices */
 private ProgressDialog pDialog;

 JSONParser jsonParser = new JSONParser();
 EditText inputdtestab;
  EditText inputdata;
  EditText inputhora;
 EditText quantidade;
 EditText etDate;
 Button change_date;

 String id2;
 String data;
 String data2;

   int Date_Dialog_ID=0;

  int cDay,cMonth,cYear; // this is the instances of the current date
 Calendar cDate;
  int sDay,sMonth,sYear; // this is the instances of the entered date




  // url to create new product
  private static String url_create_product =       "http://10.0.2.2/webprojecto4/inserir_lin_doc.php";

 // JSON Node names
 private static final String TAG_SUCCESS = "success";
  private static final String TAG_ID = "id";

 private static final String DATA = "dt";
 private static final String DATA2 = "dt2";

 @SuppressLint("NewApi")
 @Override
  public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.add_linha);


 Intent i = getIntent(); 
 id2 = i.getStringExtra(TAG_ID);
 data = i.getStringExtra(DATA);
 data2 = i.getStringExtra(DATA2);



 /** WebServices */
 inputdtestab= (EditText) findViewById(R.id.editestab);
 inputdata = (EditText) findViewById(R.id.editdata);
 inputhora = (EditText) findViewById(R.id.edithora);
 quantidade = (EditText) findViewById(R.id.editquantidade);

 inputhora.setText(hr);


 // Create button
Button btnCreateProduct = (Button) findViewById(R.id.button2);

 // button click event
btnCreateProduct.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View view) {
    // creating new product in background thread
    new CreateNewProduct().execute();
}
 });


  updateButtonState();

  }

 //restriçoes ver
private boolean checkEditText(EditText edit) {
return edit.getText().length() == 0;
}



 void updateButtonState() {
if(checkEditText(inputdtestab) && checkEditText(quantidade))
{
inputdtestab.setError("yipikaei");
quantidade.setError("mudfukkerrr");
}
else{
    Button btnCreateProduct = (Button) findViewById(R.id.button2);
btnCreateProduct.setVisibility(View.visible);

    }
 } 






  private OnDateSetListener onDateSet=new OnDateSetListener() {
 @Override
 public void onDateSet(DatePicker view, int year, int monthOfYear, 
  int dayOfMonth) {
 // TODO Auto-generated method stub
 System.out.println("2");
 sYear=year;
 sMonth=monthOfYear;
  sDay=dayOfMonth;
 updateDateDisplay(sYear,sMonth,sDay);
 }
 };




/**
 * Background Async Task to Create new product
 * */
 class CreateNewProduct extends AsyncTask<String, String, String> {

/**
 * Before starting background thread Show Progress Dialog
 * */
@Override
protected void onPreExecute() {
    super.onPreExecute();
    pDialog = new ProgressDialog(Newlin_ProductActivity.this);
    pDialog.setMessage("Creating Product..");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(true);
    pDialog.show();
}

/**
 * Creating product
 * */
protected String doInBackground(String... args) {
    String id_estab = inputdtestab.getText().toString();
    String quantidades = quantidade.getText().toString();
    String data = inputdata.getText().toString();
    String hr = inputhora.getText().toString();





    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
   params.add(new BasicNameValuePair("id_cab_doc", id2));
   params.add(new BasicNameValuePair("num_lin", ""));//ir buscar criar
   params.add(new BasicNameValuePair("id_produto", "00000"));
   params.add(new BasicNameValuePair("id_tipo_produto", "00"));
   params.add(new BasicNameValuePair("id_estab", id_estab));
   params.add(new BasicNameValuePair("quantidade", quantidades));
   params.add(new BasicNameValuePair("dt", data));
   params.add(new BasicNameValuePair("hr", hr));


    // getting JSON Object
    // Note that create product url accepts POST method
    JSONObject json = jsonParser.makeHttpRequest(url_create_product,
            "POST", params);

    // check log cat fro response
    Log.d("Create Response", json.toString());

    // check for success tag
    try {
        int success = json.getInt(TAG_SUCCESS);

        if (success == 1) {
            // successfully created product
            Intent i = new Intent(getApplicationContext(), Linhas_pesagem.class);
            i.putExtra(TAG_ID, id2);
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(i);

            // closing this screen
            finish();
        } else {
            // failed to create product
            Intent i = new Intent(getApplicationContext(), Linhas_pesagem.class);
            i.putExtra(TAG_ID, id2);

            startActivity(i);
            finish();
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return null;
}

/**
 * After completing background task Dismiss the progress dialog
 * **/
protected void onPostExecute(String file_url) {
    // dismiss the dialog once done
    pDialog.dismiss();
}

}


}

2 个答案:

答案 0 :(得分:0)

setViewVisibility表示您需要定义视图的ID。相反,使用:

yourButton.setVisibility( View.(GONE, HIDDEN, VISIBLE, ...))

答案 1 :(得分:0)

&#34;所以我的问题是以下我做了2个功能,目标是返回如果一个edittext有写的东西,如果它有我想让它按钮可见如果不是我想要按钮保持隐形。但是这并不是我的所有代码。#34;

所以基本上你想在EditText视图中提供输入值时显示按钮。然后隐藏按钮。

按如下方式修改updateButtonState()方法:

void updateButtonState() {
    // Create button
    Button btnCreateProduct = (Button) findViewById(R.id.button2);

    if(checkEditText(inputdtestab) && checkEditText(quantidade)) {
        inputdtestab.setError("yipikaei");
        quantidade.setError("mudfukkerrr");

        // ==========================================
        // make the button invisible.
        btnCreateProduct.setVisibility(View.INVISIBLE); // or use View.GONE
    } else {

        // ==========================================
        // make button visible.
        // use the method "setVisibility", not "setViewVisibility"
        // and "VISIBLE" in "View.VISIBLE" is in full cap:
        btnCreateProduct.setVisibility(View.VISIBLE);
    }
}

要使按钮不可见,请写下btnCreateProduct.setVisibility(View.INVISIBLE);

如果您希望按钮在空间不可见时占用空间,则可以使用View.GONE代替View.INVISIBLE

更新

要在填写EditText时立即显示按钮,您必须聆听EditText的文本更改。首先,您实施TextWatcher

private TextWatcher myTextWatcher = new TextWatcher() {
  public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {}
  public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {}

  public void afterTextChanged(Editable editable) {
    // invoke the following method here:
    updateButtonState();
  }
};

然后将观察者添加为EditText的两个监听器。

inputdtestab.addTextChangedListener(myTextWatcher);
quantidade.addTextChangedListener(myTextWatcher);