我已經給我的代碼below.I只是想創建一個自定義對話框android.whenever我點擊按鈕時,它會顯示一個自定義對話框box.i已創建一個XML「alert.xml」。點擊按鈕後我將展示從string.xml我在Textview的settext(charSeq)方法上得到空指針異常?
public class TriangleActivity extends Activity implements View.OnClickListener{
/** Called when the activity is first created. */
private Button bt;
private Dialog dialog;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bt=(Button) findViewById(R.id.button1);
bt.setOnClickListener(this);
//Context mContext = getApplicationContext();
dialog = new Dialog(TriangleActivity.this);
dialog.setContentView(R.layout.alert);
dialog.setTitle("This is my custom dialog box");
TextView t=(TextView) findViewById(R.id.tv1);
t.setText(getString(R.string.h));
}
public void onClick(View v)
{
dialog.show();
}
}
main.xml中
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<Button
android:id="@+id/button1"
android:layout_width="60dp"
android:layout_height="60dp"
/>
</LinearLayout>
alert.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbars="vertical" >
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbarAlwaysDrawVerticalTrack="true" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tv1" >
</TextView>
</LinearLayout>
</ScrollView>
string.xml
內容<?xml version="1.0" encoding="utf-8"?>I am getting
<resources>
<string name="hello">Hello World, TriangleActivity!</string>
<string name="app_name">Triangle</string>
<string name="h">The Royal Society of Chemistry’s interactive periodic table which </string>
</resources>
它顯然沒有在查找中找到控件(錯誤之前的行)。您應該始終對可以爲空btw的項目執行空檢查。遵循是一個好習慣。另外 - 它發現按鈕好嗎? – tsells
嘗試使用'this.getResources()。getString((R.string.h)'而不是'getString(R.string.h)' – Praveenkumar