Question

While I was reading a tutorial for how to create layouts dynamically, I found that the buttons in the xml file are defined as a view as shown below, and not as I expected to be defined as buttons. Are either ways of defining a view element the same or there are differences?

xml:

<LinearLayout 
            android:id="@+id/linearLayout00"
            android:layout_height="wrap_content" 
            android:layout_width="match_parent"
            android:orientation="horizontal">
            <Button android:text="Add View" 
                android:id="@+id/addBtn00" 
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight=".5" />
            <Button 
                android:text="Remove View" 
                android:layout_height="wrap_content"
                android:id="@+id/removeBtn00" 
                android:layout_width="0dp"
                android:layout_weight=".5" />
        </LinearLayout>

Java_Code:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    View buttonAdd = findViewById(R.id.add);
    buttonAdd.setOnClickListener(this);

    View buttonRemove = findViewById(R.id.remove);
    buttonRemove.setOnClickListener(this);
Was it helpful?

Solution

The Button class is a subclass of View. Polymorphism allows us to use subclasses in place of the parent class, however, you will only be able to access the methods from the View class, not any methods specific to the Button class.

This means you will not be able to call methods like setText() (which the Button class inherits from TextView, which in turn inherits from View)

If you want to cast it to a button you should write:

Button buttonAdd = (Button) findViewById(R.id.add);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top