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
Solution 1:
Try like this :
private LinearLayout lLayout;
private EditText lEditText;
private Button lButton;
@OverridepublicvoidonCreate(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());
TextViewtextView=newTextView(this);
textView.setText("Text New");
}
private OnClickListener onClick() {
returnnewOnClickListener() {
@OverridepublicvoidonClick(View v) {
lLayout.addView(createTextView(lEditText.getText().toString()));
}
};
}
private TextView createTextView(String text) {
finalLayoutParamsloutParams=newLayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
finalTextViewtextView=newTextView(this);
textView.setLayoutParams(loutParams );
textView.setText("Text is " + text);
return textView;
}
Solution 2:
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
Post a Comment for "Unable To Display Textview On Button Click In Android"