【问题标题】:XML / Java Button Click to change TextViewXML/Java 按钮点击更改 TextView
【发布时间】:2015-08-18 10:22:25
【问题描述】:

我对 Java 编码非常陌生,我正在尝试使用按钮按下(在 Android 应用程序中)来更新文本视图。每当我尝试按下按钮时,我当前使用的代码都会导致我的应用程序崩溃。

这是我的 XML

<LinearLayout>
<TextView
        android:id="@+id/myTextView_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="0" />

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="calculateNewNumber"
        android:text="Calculate New Number" />
</LinearLayout>

这是我的 Java

package com.example.android.myapp;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

int startNumber = 0;

public void calculateNewNumber(View view) {
    startNumber = startNumber + 1;
    display(startNumber);
}

private void display(int number) {
    TextView myTextView = (TextView) findViewById(
            R.id.myTextView_text_view);
    myTextView.setText("" + number);
}
}

感谢您提供的任何帮助。

【问题讨论】:

  • 它会给你什么样的错误?
  • 请看一下stackoverflow.com/questions/23353173/… 并告诉我们您的错误
  • 我已经用你的代码测试过它工作正常。您是否将 android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" 设置为线性布局?

标签: java android xml button textview


【解决方案1】:

代码本身运行良好,所以问题一定出在您的 XML 上,假设您已在此处提供了完整的代码。

使用此 XML,您的 MainActivity 代码对我来说可以正常工作。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <LinearLayout
        android:layout_height="wrap_content"
        android:layout_width="fill_parent">
        <TextView
            android:id="@+id/myTextView_text_view"
            android:layout_width="60dp"
            android:layout_height="wrap_content"
            android:text="0" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="calculateNewNumber"
            android:text="Calculate New Number" />
    </LinearLayout>

</RelativeLayout>

【讨论】:

  • 例外只是点击按钮,所以我猜布局工作正常
  • 您真的尝试过我发布的 XML 吗?由于您没有提供任何错误详细信息,我不能肯定地说,但您的异常可能会引发,因为您的 LinearLayout 缺少必需的字段,如高度、宽度等......
猜你喜欢
  • 2012-12-24
  • 2021-05-21
  • 1970-01-01
  • 1970-01-01
  • 2017-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多