user10635007
user10635007

Reputation: 57

Unable to display textview on button click in android

I want to create this textview, and then display it after this button is clicked, but no textview is displayed.

I dont't want to use findViewById(), if possible, because I want to create a new textview every time the button is pressed. I've tried making a linear layout first, but I've seen a lot of websites say that you don't need to, and I would prefer not to. Any advice would be helpful. Thank you.

EditText name=layout.findViewById(R.id.enterName);
        final String Name=name.getText().toString();
        Button create=layout.findViewById(R.id.create);
        create.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TextView ProgrammaticallyTextView = new TextView(MainActivity.this);
                ProgrammaticallyTextView.setText(Name);
                ProgrammaticallyTextView.setTextSize(22);
                popup.dismiss();
            }
        });

There are no error messages and the logcat doesn't say that anything is wrong.

Upvotes: 1

Views: 413

Answers (2)

Vinay Hegde
Vinay Hegde

Reputation: 1460

Try like this :

private LinearLayout lLayout;
private EditText lEditText;
private Button lButton;

@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);
   lLayout = (LinearLayout) findViewById(R.id.linearLayout);
   lButton = (Button) findViewById(R.id.button); 
   lEditText = (EditText) findViewById(R.id.editText);
   lButton.setOnClickListener(onClick());
   TextView textView = new TextView(this);
   textView.setText("Text New");
}

private OnClickListener onClick() {
   return new OnClickListener() {
    @Override
    public void onClick(View v) {
        lLayout.addView(createTextView(lEditText.getText().toString()));
    }
};
}

private TextView createTextView(String text) {
   final LayoutParams loutParams = new 
   LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
   final TextView textView = new TextView(this);
   textView.setLayoutParams(loutParams );
   textView.setText("Text is " + text);
   return textView;
}

Upvotes: 1

gsabbih
gsabbih

Reputation: 1

Use the activity's findViewById() method to reference your layout views. For example, you can replace

EditText name=layout.findViewById(R.id.enterName);
Button create=layout.findViewById(R.id.create);

with

EditText name=getActivity().findViewById(R.id.enterName); 
Button create=getActivity().layout.findViewById(R.id.create);

Note: if you are not using fragments then there is no need to use getActivity since findViewById() is a method of the superclass AppCompactActvity( or Activity).

I guess your code is not working because the Button View and Editext Views have not been reference when activity starts for the oncreate() method

Upvotes: 0

Related Questions