2016-08-02 4 views
0

ここで投稿の一部を読みましたが、問題を解決していないようです。TextViewを表示するときにダイアログフラグメント(カスタムレイアウト)が機能しない

enter image description here

MainActivity.java

public class MainActivity extends AppCompatActivity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    Button button=(Button)findViewById(R.id.button2); 
    button.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      dialog my_alert=new dialog(); 
      my_alert.show(getFragmentManager(),""); 
     } 
    }); 

} 
} 

dialog.java

public class dialog extends DialogFragment { 

@Override 
public Dialog onCreateDialog(Bundle savedInstanceState) { 
    AlertDialog.Builder build=new AlertDialog.Builder(getActivity()); 
    LayoutInflater inflater; 
    View v; 
    inflater=getActivity().getLayoutInflater(); 
    v=inflater.inflate(R.layout.dialog_layout,null); 
    build.setView(v); 
    return build.create(); 

} 

}

上記コーディングはwoはあります私はtextviewを追加する前にrking。

しかし、私がしたいのは、カスタムレイアウトでtextviewを表示することです。 build.setView(v)の下に次のコーディングを追加すると、終了します。

build.setView(v) 
TextView tv=(TextView)getActivity().findViewById(R.id.textView); 
tv.setText("my text here"); 
return build.create(); 

Logcatエラー

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference 
+0

AlertDialog.Builder builder = new AlertDialog.Builder(YourActivity.this); DialogFragmentからビルダーを拡張したり、アクティビティーにユーザーを追加したりしないでください。 builder.setView()を使用してカスタムビュー – Bob

+0

を使用すると、mainactivityを内部に配置する必要があります。私はJavaクラスを分離したいと思います。あなたのソリューションについて、もっと説明できますか? – gosulove

+0

dialog_layout.xmlにIDが "textView"のTextViewがあるかどうかを確認します – sJy

答えて

1

onCreateDialog(でこれを行います)

View v; 
inflater=getActivity().getLayoutInflater(); 
v=inflater.inflate(R.layout.dialog_layout,null); 
TextView tv=(TextView)v.findViewById(R.id.textView); 
tv.setText("my text here");** 
1
<TextView 
    android:id="@+id/textView" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" /> 

テレビでは、レイアウトdialog_layoutでのTextViewのラベルを定義する必要がありnull.Maybeです。

このコードを使用してください。

1

私はエラーがここにあると思う:

TextView tv=(TextView)getActivity().findViewById(R.id.textView); 

TextView tv=(TextView)v.findViewById(R.id.textView); 
0

、これを試してみてください V(あなたが膨らまいるレイアウト)

で getActivity() を置き換えますあなたのダイアログビューはdialog_layoutです。つまり、dialog_layoutにテキストビューがあります。私は正しい?では、dialog_layoutビューからテキストビューが表示されないのはなぜですか?

build.setView(v) 
TextView tv=(TextView)getActivity().findViewById(R.id.textView); //--> which view is the textview from? 
tv.setText("my text here"); 
return build.create(); 
+0

はい私はそこから取得しています。問題は、getActivity()からvへの変更です。 – gosulove

関連する問題