【问题标题】:how to add button in android studio?如何在android studio中添加按钮?
【发布时间】:2017-11-11 21:36:18
【问题描述】:

每当我点击提交按钮时,应用程序就会崩溃,我是一个初学者,并关注了一个 youtube 视频

这里是代码

public void onButtonClick(View v) {
    EditText e1 = (EditText) findViewById(R.id.textView);
    EditText e2 = (EditText) findViewById(R.id.textView2);
    TextView t1 = (EditText) findViewById(R.id.textView3);
    int num1 = Integer.parseInt(e1.getText().toString());
    int num2 = Integer.parseInt(e2.getText().toString());
    int sum = num1 + num2;
    t1.setText(Integer.toString(sum));
}

【问题讨论】:

  • 任何错误日志?如何将onButtonClick 方法设置为按钮?你的布局 xml 是什么样的?

标签: android android-button


【解决方案1】:

要显示按钮,请在 XML 文件中添加一个按钮。

<Button
     android:id="@+id/button_id"
     android:layout_height="wrap_content"
     android:layout_width="wrap_content"
     android:text="Button" />

对于OnClick action,在对应activity中的按钮对象上设置OnClickListener

    public class MyActivity extends Activity {
         protected void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);

             setContentView(R.layout.layout_id);

             final Button button = findViewById(R.id.button_id);
             EditText e1 = (EditText) findViewById(R.id.textView);//Make Sure that this is EditText or TextView
             EditText e2 = (EditText) findViewById(R.id.textView2);
             TextView t1 = (EditText) findViewById(R.id.textView3);
             int num1 = Integer.parseInt(e1.getText().toString());
             int num2 = Integer.parseInt(e2.getText().toString());
             int sum = num1 + num2;
             button.setOnClickListener(new View.OnClickListener() {
                 public void onClick(View v) {
                     t1.setText(Integer.toString(sum));
                 }
             });
         }
     }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-08
    • 1970-01-01
    • 2022-12-10
    • 1970-01-01
    • 2014-10-07
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    相关资源
    最近更新 更多