我想在单击按钮后打开自定义对话框。 XML中按钮的代码是:
<Button
android:id="@+id/Button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/BorderMargin"
android:layout_marginRight="@dimen/BorderMargin"
android:background="#D2D2D2"
android:onClick="openDialog1"
android:padding="17dip"
android:text="@string/ButtonAdd" />
单击后,按钮打开方法“openDialog1”:
public void openDialog1(View view) {
final Dialog dialog = new Dialog(this.getApplicationContext());
dialog.setContentView(R.layout.dialogbrand_layout);
dialog.setTitle("Hello");
TextView textViewUser = new TextView(getApplicationContext());
textViewUser = (TextView) findViewById(R.id.textBrand);
textViewUser.setText("Hi");
dialog.show();
}
我尝试执行此cose,但应用程序在textViewUser.setText上崩溃
有什么想法吗?
答案 0 :(得分:3)
您可以找到设置为活动的当前视图层次结构的ViewById。
在您的情况下,您应该使用活动上下文,并使用对话框对象来初始化textview。
您也可以删除最终修饰符。
public void openDialog1(View view) {
Dialog dialog = new Dialog(ActivityName.this);
dialog.setContentView(R.layout.dialogbrand_layout);
dialog.setTitle("Hello");
TextView textViewUser = (TextView) dialog.findViewById(R.id.textBrand);
textViewUser.setText("Hi");
dialog.show();
}
When to call activity context OR application context?
检查上述链接以及commomsware的答案,以了解何时使用活动上下文或应用程序上下文。
答案 1 :(得分:0)
您不应该使用应用程序的上下文来创建对话框/视图。
变化:
final Dialog dialog = new Dialog(this.getApplicationContext());
对此:
final Dialog dialog = new Dialog(view.getContext());
//or
final Dialog dialog = new Dialog(this); //'this' refers to your Activity
答案 2 :(得分:0)
Waqas是对的,而且你覆盖了以编程方式创建的textViewUser
:“textViewUser = new TextView(getApplicationContext());
”并在视图层次结构中找到了一个实例:“textViewUser = (TextView) findViewById(R.id.textBrand);
”。
似乎textViewUser
为空。
您是否尝试从视图dialogbrand_layout
获取此TextView?如果是,则确保您的textViewUser
为空,因为此TextView不在您的视图层次结构中。
答案 3 :(得分:0)
您确定textBrand textview位于您为活动设置的contentView中。
textViewUser = (TextView) findViewById(R.id.textBrand);
findViewById调用返回null。 如果R.layout.dialogbrand_layout具有textBrand textview,则用
替换上面的行 textViewUser = (TextView)dialog.findViewById(R.id.textBrand);