Josh Wein
Josh Wein

Reputation: 80

Making a button that creates an object and displays it when clicked

I have a program that handles song objects with some fields and playlist objects that are arrays of the songs. I have a perfectly functioning java programming that does what I need it to do but I'm trying to convert it into an Android app and it's making me want to throw my computer out the window. I don't really know XML but I've gotten the basics such as creating buttons etc.

I have a button in the layout file that I implemented as follows:

<Button
    android:id="@+id/button1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:text="@string/Button" 
    android:onClick="newPlaylist"/>
<TextView
    android:id="@+id/textView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/button1"
    android:layout_below="@+id/button1" />

In my main file I have:

public void newPlaylist(View view){
    Playlist list1 = new Playlist("First Playlist");
    TextView first = (TextView) findViewById(R.id.textView1);
    first.setText(list1.getName());     
}

Edit: I was able to add a little to the newPlaylist method. Now when I click the button it displays the name of the playlist, but I still want to edit it and be able to have multiple playlists on the screen to manipulate.

All I want to do is display the playlist name as either a text or label that is clickable so that the name can be changed and I can move on from here.

Upvotes: 1

Views: 81

Answers (1)

Steven
Steven

Reputation: 271

The Android documentation on the button component might help you with your problem.

I assume that your Playlist class looks something like this

public class Playlist {
    private String name;

    public Playlist(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

If it does, then your method for handling the button click should look like this.

public void newPlaylist(View view) {
    Playlist playlist = new Playlist("My First Playlist!"); // Create our playlist object
    // Since button is the only component that uses 'newPlaylist' as a click listener, the view will always be the button
    Button button = (Button) view; // We cast the view to button
    button.setText(playlist.getName()); // This edits the button text, might want to create a TextView for this
}

Upvotes: 2

Related Questions