So I’ve been looking around for android tutorials, help questions, etc.. I keep running into questions or tutorials hard for me to understand.
Here’s my questions:
-
When I create an item in the visual designer, piece of code will be created in the .xml.
How can I get the ID of that item to use it in the .java file later? -
How can I add callbacks when let’s say a button gets clicked?
Here’s what I have so far:
.java
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.Button;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void Button_click_callback() // Where to add the callback in the .xml?
{
// How to get button ID and change the text of it?
//Knowing this will help me A LOT!
}
}
.xml
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="79dp"
android:layout_marginTop="32dp"
android:text="Button" />
Step #1: Ensure that you have assigned an ID for the widget in the designer (in your XML above, you will see this as
android:id="@+id/button1)Step #2: In Java, you can get at the Java object for that widget by calling
findViewById(R.id.button1)at some appropriate time (e.g., from anActivity, sometime after you callsetContentView()).Generally, there is a setter method for this, such as
setOnClickListener()that you can call on theButtonyou retrieved byfindViewById().In the specific case of click events on widgets hosted by activities, there is also an
android:onClickattribute you can have in the XML, which supplies the name of a method on yourActivitythat will get called when the widget is clicked, instead of your having to use the setter.