gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:31:58 24 4
gpt4 key购买 nike

我有一个非常简单的应用程序,它接受用户文本作为输入并返回它。该应用程序似乎可以正常工作,但我希望在返回的用户输入下方有一个按钮。现在它只是返回没有按钮的文本,尽管我已经将按钮添加到 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com