简体   繁体   中英

Set Custom Text in a Custom Alert-dialog (Android-Studio)

I have this code for my custom dialog: package com.example.ortel.tagnet;

import dev.niekirk.com.instagram4android.requests.payload.InstagramUser;

public class CustomDialogClass extends Dialog implements
    android.view.View.OnClickListener {

  public Activity c;
  public Dialog d;
  public Button yes, no;
  public EditText name;
  public CustomDialogClass(Activity a) {
    super(a);
    // TODO Auto-generated constructor stub
    this.c = a;
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.custon_dialog);
    yes = (Button) findViewById(R.id.btn_yes);
    no = (Button) findViewById(R.id.btn_no);
    name = (EditText) findViewById(R.id.name);
    yes.setOnClickListener(this);
    no.setOnClickListener(this);

  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
    case R.id.btn_yes:
      c.finish();
      break;
    case R.id.btn_no:
      dismiss();
      break;
    default:
      break;
    }
    dismiss();
  }
  public String getFirst(String s) {
    name.setText(s);
    return s;
  }

}

In my name class, I call...

        CustomDialogClass cdd = new CustomDialogClass((Activity) context);
        cdd.getFirst("test");
        cdd.show();

I want to set the text (located by the id 'name') to 'test'.

When I run this code, I get the following error:

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

What is the problem?

EDIT: Please tell me if you need any more info!

You try:

public void getFirst(String s) {
    name.setText(s);
  }

I think you change function name from: [getFirst] to [setNameTitle], your name function not clear.

I just figured it out!

cdd.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        cdd.getWindow().getAttributes().windowAnimations = R.style.dialog_animation;
        cdd.show();
        cdd.getFirst("test");

cdd.show();

Must come first!

cdd.findViewById(R.id.name);

At this way you can acess any object by id from your layout file:

cdd= new Dialog(Activity.this);
cdd.setContentView(R.layout.layout_file);
cdd.findViewById(R.id.name);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM