如何解决为什么点击按钮不显示你好?
我想要一个包含 EditText 和按钮的程序。如果 EditText 字符串等于“h”,我想通过单击按钮来显示一条消息。 但它不起作用。无论 EditText 输入是否等于“h”,它都会打印“hello”。
package com.mycompany.myapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.*;
import android.text.*;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText tex=(EditText)findViewById(R.id.etx);
final String vorodi=tex.getText().toString();
Button b = (Button) findViewById(R.id.bt);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (vorodi.equals("h")){
Toast.makeText(MainActivity.this,"hello",Toast.LENGTH_LONG).show();
}
}
});
}
}
解决方法
移动
final String vorodi=tex.getText().toString();
在您的 onClick()
函数中,以便您在点击时捕获编辑文本的内容,而不是在 onCreate()
中设置用户界面时。
1-to layout 写这个代码
-join
2-在您的活动或片段中使用此代码
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_centerInParent="true">
<EditText
android:id="@+id/editText"
android:layout_width="180dp"
android:layout_height="wrap_content"
android:hint="name"/>
<Button
android:id="@+id/button"
android:layout_width="180dp"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="click"/>
</LinearLayout>
</RelativeLayout>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。