【问题标题】:Open a custom dialog after click a button Android单击按钮后打开自定义对话框 Android
【发布时间】:2013-06-14 08:39:19
【问题描述】:

我想在单击按钮后打开一个自定义对话框。 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();
}

我尝试执行此操作,但应用程序在 textViewUser.setText 上崩溃

有什么想法吗?

【问题讨论】:

标签: android android-layout button dialog android-4.2-jelly-bean


【解决方案1】:

您可以找到当前视图层次结构设置为活动的ViewById。

在您的情况下,您应该使用活动上下文并使用对话框对象来初始化 textview。

你也可以去掉final修饰符。

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的答案,以了解何时使用活动上下文或应用程序上下文。

【讨论】:

    【解决方案2】:

    您不应该使用应用程序的上下文来创建对话框/视图。

    变化:

    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
    

    【讨论】:

      【解决方案3】:

      Waqas 是对的,但您还可以覆盖您以编程方式创建的 textViewUser:“textViewUser = new TextView(getApplicationContext());”,并在您的视图层次结构中找到一个实例:“textViewUser = (TextView) findViewById(R.id.textBrand);”。

      textViewUser 似乎为空。 您是否尝试从 dialogbrand_layout 视图中获取此 TextView?如果是,则可以确定您的 textViewUser 为 null,因为此 TextView 不在您当前的视图层次结构中。

      【讨论】:

        【解决方案4】:

        您确定 textBrand textview 在您为活动设置的 contentView 内吗?

         textViewUser = (TextView) findViewById(R.id.textBrand);
        

        findViewById 调用返回 null。 如果 R.layout.dialogbrand_layout 有 textBrand textview 然后用

        替换上面的行
         textViewUser = (TextView)dialog.findViewById(R.id.textBrand);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-06-05
          • 2014-03-08
          • 1970-01-01
          • 2012-08-08
          • 2015-09-13
          • 2017-08-16
          相关资源
          最近更新 更多