2017-03-07 203 views
-2

我創建了一個按鈕,點擊後會打開一個AlertDialog,用於輸入位置是全局變量的輸入。問題是在將可變位置分配給onClickListener之外的值,它仍然顯示爲空...全局變量值沒有改變

String location = ""; 
TextView details; 
TextView cityName; 
TextView temp; 
Button locationInput; 
static String tempString = ""; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    details = (TextView) findViewById(R.id.details_field); 
    cityName = (TextView) findViewById(R.id.city_name); 
    temp = (TextView) findViewById(R.id.current_temperature_field); 
    locationInput = (Button) findViewById(R.id.button_location_input); 


    locationInput.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      final AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this); 
      LayoutInflater inflater = MainActivity.this.getLayoutInflater(); 
      View view = inflater.inflate(R.layout.dialog_box,null); 
      alertDialog.setView(view); 
      alertDialog.setTitle("Enter the location"); 

      final EditText locationInput = (EditText) view.findViewById(R.id.location_input); 
      locationInput.setInputType(InputType.TYPE_CLASS_TEXT); 

      alertDialog.setPositiveButton("Accept", new DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface dialog, int which) { 
        location = locationInput.getText().toString(); 
        Log.i("Location",location); 
        locationInput.setVisibility(View.GONE); 
        tempString = location; 
        dialog.dismiss(); 
       } 
      }); 

      alertDialog.setNegativeButton("Deny", new DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface dialog, int which) { 

        dialog.dismiss(); 
       } 
      }); 

      AlertDialog create = alertDialog.create(); 
      create.show(); 
     } 
    }); 
+0

工作,你必須聲明的「位置」變量作爲字符串和能源部它全局聲明? –

+0

喲完成它...說,有問題.. –

+0

請再次檢查editText R.id.location_input是否存在於各自的佈局或不。用ctrl + B檢查。有時微小的錯誤使空指針Exp –

回答

0

請更換從AlertDialog代碼對話框,如下,它應該是你

Dialog dialog = new Dialog(context); 
     dialog.setContentView(R.layout.custom); 
     dialog.setTitle("Title..."); 

     // set the custom dialog components - text, image and button 
     TextView text = (TextView) dialog.findViewById(R.id.text); 
     text.setText("Android custom dialog example!"); 
     ImageView image = (ImageView) dialog.findViewById(R.id.image); 
     image.setImageResource(R.drawable.ic_launcher); 

     Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK); 
     // if button is clicked, close the custom dialog 
     dialogButton.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       dialog.dismiss(); 
      } 
     }); 

     dialog.show(); 
+0

我沒有得到它...我想使用位置變量,用戶在API網址中的警報對話框中輸入獲取天氣..所以這將如何幫助......? –