JDS
JDS

Reputation: 16978

Android: dynamic text creation?

Let's say I have some strings in Java that I've retrieved from a web script. It doesn't matter really, they're just strings stored in variables.

Now my question is how to dynamically append them to the application (to show the user) and possibly style their position, from Java.

To draw an analogy, I want to do something similar to the following in JavaScript:

var text = document.createElement('div'); 
text.appendChild(document.createTextNode("some string")); 
text.style.position = "whatever";
// etc, more styling
theDiv.appendChild(text); // add this new thing of text I created to the main application for the users to see

I've looked into the TextView, and I don't seem to be using it properly (I don't understand the constructor I guess?). What I want to try right now is to have the user press a button in my application and then have some text dynamically generated. Here's what I've been trying:

search_button = (Button) findViewById (R.id.backSearchButton);
        search_button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {


            String test = new String("testing!"); 

            TextView test2 = new TextView(this);    //constructor is wrong, this line gives me an error

            test2.setText(test); 

            setContentView(test2); 

        }
    });

As you can probably tell, I don't come from much of a Java background. I'm just trying to draw parallels to stuff I would want to do for a web app.

Thanks for the help.

Upvotes: 1

Views: 773

Answers (3)

Jack Smartie
Jack Smartie

Reputation: 443

I'm new to Java and Android, myself. But I'll give your question a try.

  1. You have to decide if you want to create the TextView in XML or dynamically in Java. I think creating it in XML in the layout creator is better.

  2. I don't think you should be using setContentView(test2).

  3. If you create a TextView dynamically, I don't think you need to put anything in its constructor. But you do have to add the TextView to the parent view. In other words, let's say you have a LinearLayout somewhere in your layout. You have to do: linearLayout1.add(myTextView) or something.

The rest of your code seems fine. But then again, I'm still new to this, myself. Let me know how helpful this answer is, I'll try Googling for more help if it's not enough.

Upvotes: 1

Peter Knego
Peter Knego

Reputation: 80330

Try:

TextView test2 = new TextView(ParentActivity.this);

replace "ParentActivity" with the name of your activity.

Upvotes: 3

fleetway76
fleetway76

Reputation: 1640

your this pointer is a reference to the OnClickListener that you have anonymously created. You need a pointer to the containing Activity.

You would probably be better constructing your text view in the onCreate of your activity and just setting the text from your onClick method

Upvotes: 1

Related Questions