1

I am working on an android app in java, and ive created a sub-class of android.support.v7.widget.AppCompatButton, because youre not supposed to directly subclass Button. When i create the subclass object (hencforth refered to as "subButton") and add it to the activity via XML, the item looks and acts like a button, however when i do so via Java (programatically) , it looks and acts like a textView instead.

my XML is

  <com.example.appName.subButton
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="xmlTestItem"/> 

While my Java is

 subButton testItem = new subButton(getApplicationContext());
    testItem.setText("javaTestItem");
    testItem.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT ,ViewGroup.LayoutParams.MATCH_PARENT));
    mainListScroll.addView(testItem);

but it still only displays text instead of a button. Any clues?

  • What happens if you change `getApplicationContext()` to `this`? – clownba0t Jan 05 '18 at 03:40
  • It fixes the issue and makes the button act like a regular button. Thanks! if you wanna submit this as an answer in statement form instead of question form, ill mark you as correct – GodOfPlutonium Jan 05 '18 at 03:57

1 Answers1

0

The issue is most likely caused by the use of the application context rather than activity context when instantiating the subButton instance. In particular, the themes associated with these contexts, which are used when instantiating view components, are usually different.

As a general rule you should use the context directly available to you at the time. In an activity, this means making use of its own context via this.

For more details, see this classic post: https://stackoverflow.com/a/7298955/2259854

clownba0t
  • 1,003
  • 9
  • 11