android - 如何让我的 Android Activity 使用它的 xml 文件?

标签 android android-layout android-activity

我有一个非常简单的应用程序,它接受用户文本作为输入并返回它。该应用程序似乎可以正常工作,但我希望在返回的用户输入下方有一个按钮。现在它只是返回没有按钮的文本,尽管我已经将按钮添加到 Activity 的 xml 文件中。我什至在 xml 文件的图形 View 上看到了按钮,所以我知道问题一定是找到一种方法将 xml 文件与 DisplayMessageActivity.java 文件连接起来。下面是我的 DisplayMessageActivity.java 文件的 fragment ,我认为我做错了什么。也许我不应该调用 setcontentview 函数?

@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);      
    // Get the message from the intent
    Intent intention1=getIntent();
    final String message = intention1.getStringExtra(MainActivity.EXTRA_MESSAGE);


    // Create the text view
    TextView textView = new TextView(this);
    textView.setTextSize(40);

   // Set the text view as the activity layout
      textView.setText(message);
      setContentView(textView);



    }

最佳答案

为什么要调用 setContentView(TextView)?您必须膨胀代表您的 Activity 布局的完整布局文件,即;

setContentView(R.layout.activity_layout).  //Inflate the layout of your activity

然后你必须从那个父布局中膨胀你的按钮,这样你就会有类似的东西

Button button = (Button) findViewById(R.id.button1);  //Inflate the button that is inside 
                                                      //that layout

你的 onCreate 应该看起来更像这样

private Button button;

protected void onCreate(Bundle savedInstanceState){
   setContentView(R.layout.activity_layout);   //Call this  first

   button = findViewById(R.id.button_id);
   button.setOnClickListener(this);


   //Inflate whatever other buttons/views you have inside your activity here

确保您还在同一个布局文件中为您的 Activity 定义了您。祝你好运

关于android - 如何让我的 Android Activity 使用它的 xml 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17309816/

相关文章:

java - 将堆栈大小设置为线程似乎在android中没有什么区别

android - 平台不允许 Flutter Insecure http

android - TextInputLayout 抛出 "The style on this component requires your app theme to be Theme.AppCompat (or a descendant)."

java - 如何在多个 Activity 中保持蓝牙连接?

android - 无法在循环中将多个 TextView 添加到 linearLayout

java - Android:阻止虚拟键盘上的按键

android - 如何在android中滚动时将标签从内容粘贴到屏幕顶部

android - 如何更改 Android 中的汉堡包图标(NavigationDrawer)

java - 将字符串从一个 fragment 传递到另一个 fragment

android - 关于android启动模式 "singleTask"