Question

I am trying to create a Button programmatically using a drawable selector.

After I did the configuration, I tried to set the text of the Button using setText() method but it didn't work.

Here is my code:

    Button b = new Button(this);
    int pxw = (int) getResources().getDimension(R.dimen.level_button_width);
    int pxh = (int) getResources().getDimension(R.dimen.level_button_height);
    LayoutParams lp = new LinearLayout.LayoutParams(pxw,pxh);
    lp.setMargins(8, 8, 8, 8);
    b.setLayoutParams(lp);
    b.setShadowLayer(8, 0, 0, 0xA8A8A8);
    int sdk = android.os.Build.VERSION.SDK_INT;
    if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
        b.setBackgroundDrawable(getResources().getDrawable(R.drawable.level_button));
    } else {
        b.setBackground(getResources().getDrawable(R.drawable.level_button));
    }

    b.setTextColor(0xFFFFFF);
    b.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 36);
    b.setText("heey");

    b.setOnClickListener(new OnClickListener() {                
    @Override
    public void onClick(View v) {
        startlevel(Integer.parseInt((String) ((Button)v).getText()));                   
    }
});
mLinearLevel.addView(b);

And here is my drawable:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_enabled="false"
    android:drawable="@drawable/level_button_disabled" />

<item android:state_pressed="true" 
    android:drawable="@drawable/level_button_pressed"/>

<item android:drawable="@drawable/level_button_normal"/>      
</selector>

The result is a custom button with no text.

What's wrong with it?

Thanks in advance.

Update: Check my answer below.

Was it helpful?

Solution

The solution is Color.parseColor() method. I changed it as in mohammed's comment and it worked.

b.setTextColor(Color.parseColor("#FFFFFF"));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top