开发者

failing to use R, can't manipulate UI via java code

I have multiple buttons on the same activity each invoking the method "guessMade()" when they are clicked.

Every time a button is clicked, I would like to set the name of that button as th开发者_Go百科e message that is going to be displayed in a TextView. Needless to say, TextView is also already created.

My code is as follows:

public void guessMade(View view){
    CharSequence s = ((Button)view).getText();
    TextView t = (TextView)view.findViewById(R.id.textView1);
    t.setText(s);
}

Where do I fail ?


I think you problem comes with the passed View:

  • First, you cast the passed View to a Button and get it's text. Okay until here.
  • The next step, you use the passed View to get the TextView that you want to use for displaying the Text.

The problem is, that your passed view can only be the Button or a collection of Views (a Layout).

You'll want to use

TextView t = (TextView) this.findViewById(R.id.textView1);

to get your View, since using the findViewById()-method:

Look for a child view with the given id.

Using this will work if this code is placed inside a class which extends Activity. If this code is not located in such a class, you can either:

  • Pass a Context-Object from a Activity or
  • use the getContext()-method of the passed View.


there is probably something wrong with your variable "s".

try replacing

t.setText(s);

with

t.setText("hello");

and see if it works.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜