Select Page

As I had said in the “first thoughts” about Android Development, the user interface of the app is written in Xml code. What does that really mean to the programmer? Well, it means that components such as buttons, radio buttons, textviews, etc are all going to be in the Xml file.

Using Xml Components with Java Code:

If we want to use the User Interface components in our java code. For Example, if we want to do something when a button is pressed then we must add an action listener to the button just like when create desktop applications. But first we must create an object of a button in the activities .java file, and then we must find the button from the activities .xml file and link it the button from the .java file. We do something like this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    >
<Button
        android:id="@+id/enter_Button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/enter"
        />

</RelativeLayout>

 

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;

public class MainActivity extends AppCompatActivity{
    Button enterButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setButton();
    }

    private void setButton(){
        enterButton = (Button)findViewById(R.id.enter_Button);
        enterButton.setOnClickListener(this);
    }
}

 

In the code above we can see that the “enterButton” button was set to “(Button)findViewById(R.id.enter_Button);” that line of code is the one that finds the button on the xml file. Once we find it then we can do everything that we would do to a button such as add an action listener, write code to be executed when the action listener is triggered. Hope you enjoyed this. Keep coding on!