2011-09-13 70 views
7

問題是你可以看到我不能在showDialog()之前動態地設置edittext的值。如何將文本設置爲對話框中的Edittext?

import android.app.Activity; 
import android.app.AlertDialog; 
import android.app.Dialog; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.os.Bundle; 
import android.telephony.TelephonyManager; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.widget.EditText; 
import android.widget.TextView; 


public class MainActivity extends Activity { 
private static final int DIALOG_TEXT_ENTRY = 7; 

private int user_id; 
private int dialogChoice; 
private String mobileNum; 
private EditText input2 ; 
private EditText input1 ; 
public TextView textView; 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.alert_dialog_text_entry); 
    TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); 
    mobileNum =tm.getLine1Number(); 
    // input1.setText(mobileNum); 
    textView.setText("hello"); 
    showDialog(DIALOG_TEXT_ENTRY); 

} 
@Override 
protected Dialog onCreateDialog(int i) { 


    switch (i) { 

    case DIALOG_TEXT_ENTRY: 
      LayoutInflater factory = LayoutInflater.from(this); 
      final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null); 
      input2 = (EditText) textEntryView.findViewById(R.id.number_edit); 
      input1 = (EditText) textEntryView.findViewById(R.id.username_edit); 
      textView = (TextView) textEntryView.findViewById(R.id.username_view); 
      return new AlertDialog.Builder(MainActivity.this) 
       // .setIconAttribute(android.R.attr.accountType) 
       .setTitle(R.string.alert_dialog_text_entry) 
       .setView(textEntryView) 
       .setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int whichButton) { 
          Intent i = new Intent(MainActivity.this, IccActivity.class); 
          startActivity(i); 
         /* User clicked OK so do some stuff */ 
        } 
       }) 
       .setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int whichButton) { 

         /* User clicked cancel so do some stuff */ 
        } 
       }) 
       .create(); 
    } 
    return null; 
} 

}

textView.setText("hello"); this line kills the app. 

在此先感謝。

回答

1

您應該將這一行textView.setText("hello");轉換爲onCreateDialog()方法,因爲您在初始化之前設置該值。

+0

謝謝。有用。我試圖在之前分配一個值來獲得對它的引用。 – akd

+0

現在你應該接受答案,因爲答案會以未答覆的方式流動 –

1

您還沒有初始化textView。你做的textView.setText()

textView = (TextView) textEntryView.findViewById(R.id.username_view);

0

你在你的onCreate需要這個()之前,我猜你得到NullPointerException異常?你應該首先使用你的'textView'字段。

0

查找TexView文本是在對話框中,設置的TextView 的文本試試這個link

相關問題