문제

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);
도움이 되었습니까?

해결책

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);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top