java - 无法在android中单击按钮时显示textview

标签 java android textview

我想创建这个textview,然后点击这个按钮后显示,但是没有显示textview。

如果可能的话,我不想使用 findViewById(),因为每次按下按钮时我都想创建一个新的 TextView 。我试过先做一个线性布局,但我看到很多网站说你不需要,我也不想这样做。任何意见将是有益的。谢谢。

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();
            }
        });

没有错误消息,logcat 也没有说有什么问题。

最佳答案

像这样尝试:

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;
}

关于java - 无法在android中单击按钮时显示textview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56499763/

相关文章:

android - Android 中对 TextView 的从右到左支持

java - 为什么我无法使用渐变颜色 android 更改图标颜色和文本底部导航

java - 如何解决生成 xsd 到 jaxb 对象时的冲突

android - 如何从 MySQL 到 ROOM 实现 SUM()、DAY()、MONTH() 和 YEAR()

Android - 将数据从 Activity 发送到服务

具有最大宽度的 Android TextView

android - 根据设备屏幕大小设置 Textview 大小

java - 像在 Swift/iOS 中一样在 Android 中以编程方式创建 UI 和框架

java - 优化 sieve 的代码

android - 如何解决android中的SAXParseException?