views:

315

answers:

2

I'm trying to learn how to build apps for Android.

The first simple app, which will become a component of a bigger app I hope to build, is to have a button on the screen where, when tapped, it adds something new to the view.

For instance:

Imagine a layout that only has a button:

[Create!]

When that button is pressed, the view gets a new row added to it:

[Create!]
A Something!

Upon subsequent presses, more rows are added

[Create!]
A Something!
A Something!

And so on.

I've made a LinearLayout and placed the button in it, and have attached a click listener to it. That all works great. What I can't figure out is how to get a handle on the LinearLayout in the onClick function with which I'll addView() the new TextView that says "A Something!"

Am I on the right track? What basic thing am I missing? Thanks!

A: 

This is from memory, so it may not be exactly right.

In your layout, you'll want to give the LinearLayout an id.

< LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/namehere"
... >

Then in your code you'll use findViewById to get a reference to it.

LinearLayout ll = (LinearLayout) findViewById(R.id.namehere);

ll.addView(...);

Slapout
You're right in that you can get things by id, but LinearLayout gives an error when I try to give an id to it. This was my first approach.
Josiah Kiehl
Sorry, I was thinking about FrameLayout. See http://www.kellbot.com/2009/06/android-hello-circle/ for an example.
Slapout
+1  A: 

I think you are approaching this the wrong way. You should look into ListView and SimpleArrayAdapter. This will put the elements into a list format that users will be more familiar with. Google has some good examples that use this (like their Notepad example). Especially if you are new to Android, you should look at their demos to get you through the basics. you can find them here

mtmurdock
Thanks, I will do that. I played around with ListView, and I got it to display with static data... just a hard coded array. I'll play with the examples to see how I can do this dynamically. Thanks!
Josiah Kiehl