android按钮不点击,按钮不点击在Android Studio中

这篇博客主要讲解了如何在Android应用中正确设置Button的点击事件,并在点击后将生成的随机事实值显示到TextView上。博主指出了初始化组件时的常见错误,并提供了修正后的代码示例,包括在onClick()方法中设置TextView的内容和显示Toast消息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

你Button点击正常,但最主要的是你没有fact值设置为TextView。

#。由于您已在onCreate()之外声明Button和TextView,因此无需在onCreate()内再次声明它。

用途:

mfactbutton = (Button) findViewById(R.id.button);

mfacttext = (TextView) findViewById(R.id.textView2);

相反的:

Button mfactbutton = (Button) findViewById(R.id.button);

TextView mfacttext = (TextView) findViewById(R.id.textView2);

#。在onClick()方法显示在TextViewfact值或显示Toast消息:

// TextView

mfacttext.setText(fact);

// Toast

Toast.makeText(getApplicationContext(), "Fact: " + fact, Toast.LENGTH_SHORT).show();

下面是工作的代码:

public class MainActivity extends AppCompatActivity {

private Button mfactbutton;

private TextView mfacttext;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

mfactbutton = (Button) findViewById(R.id.button);

mfacttext = (TextView) findViewById(R.id.textView2);

// now we need to make out button to click

View.OnClickListener Listener = new View.OnClickListener() {

@Override

public void onClick(View v) {

String[] facts = {

"Ants stretch when they wake up in the morning.",

"Ostriches can run faster than horses.",

"Olympic gold medals are actually made mostly of silver.",

"You are born with 300 bones; by the time you are an adult you will have 206.",

"It takes about 8 minutes for light from the Sun to reach Earth.",

"Some bamboo plants can grow almost a meter in just one day.",

"The state of Florida is bigger than England.",

"Some penguins can leap 2-3 meters out of the water.",

"On average, it takes 66 days to form a new habit.",

"Mammoths still walked the earth when the Great Pyramid was being built." };

String fact = "";

Random randomGenerator = new Random();

int randomNumber = randomGenerator.nextInt(facts.length);

fact = facts[randomNumber] + "";

mfacttext.setText(fact);

Toast.makeText(getApplicationContext(), "Fact: " + fact, Toast.LENGTH_SHORT).show();

}

};

mfactbutton.setOnClickListener(Listener);

}

}

OUTPUT:

f6ffba9cc0b3e58cbd20820a62d212e3.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值