设置文本并在android中添加监听器

时间:2014-11-10 16:11:22

标签: android listener settext

我制作了一个Android空白项目,然后在activity.xml页面中我向面板添加了按钮和TextView

如果按下某个按钮,我想在activity.java中更改活动TextView的代码,我该怎么做?

我发现的是.java文件中的id如下:

    {li> R.id.TextView1 TextView {li> R.id.Button01 Button

我想按下按钮时文本设置为“hi”,有人可以帮我这个吗? 我是新手android和谷歌搜索失败了我或使用一些我不明白的奇怪方式。我需要基础知识。

3 个答案:

答案 0 :(得分:2)

这样的事情可以做到:

    Button button; // ref to the button object
    TextView textView; // ref to the text view object

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

        button = (Button) findViewById(R.id.button); // get the button object
        textView = (TextView) findViewById(R.id.textView); // get the textView object

        button.setOnClickListener( new View.OnClickListener() { // set the click listener for the button
            @Override
            public void onClick(View view) {
                textView.setText("hi"); // that's it!
            }
        });
    }

答案 1 :(得分:1)

只需用你的oncreate代替它,你的代码就可以了。

TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity);

        Button button = (Button) findViewById(R.id.Button01); // get the button object
        textView = (TextView) findViewById(R.id.TextView1); // get the textView object

        button.setOnClickListener( new View.OnClickListener() { // set the click listener for the button
            @Override
            public void onClick(View view) {
                textView.setText("hi"); 
            }
        });
    }

答案 2 :(得分:0)

在您的活动中:

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TextView tv = (TextView) findViewById(R.id.TextView1);
    Button button = (Button) findViewById(R.id.Button01);
    button.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        tv.setText("Hi");
      }
    });
}