1

I create textView and editText in code.

           TextView textview = new TextView(getActivity());

            final EditText editText = new EditText(getActivity());
            editText.setGravity(Gravity.CENTER);

and i have style in res/values/mystyle when i add style in textView it looks like this:

 TextView textview = new TextView(getActivity(), null,  R.style.editTextStyle);

But, nothing changed. How add style in textView and editText from my code. What im doing wrong? Thanks for all!

Vlad
  • 9
  • 1
  • 4

1 Answers1

5

We cannot programmatically set styles: android set style in code. At least not yet. The information in the style xml should me moved and converted into a layout xml format.

Basically you need to create a new layout xml, which contains only one view. Here's a sample layout for a TextView:

(layout/edit_text_style.xml in my test setup)

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="#000033"
    android:textColor="#00aa00"
    android:typeface="monospace"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
</TextView>


Then the TextView should be created in the Activity code using getLayoutInflater(). Here's sample code:

(MainActivity.java using layout/main.xml in my test setup.)

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

    LinearLayout root = (LinearLayout) findViewById(R.id.root); 
    TextView test = (TextView) getLayoutInflater().inflate(R.layout.edit_text_style, null); // Magic!
    test.setText("Ah, hello World..."); // Remove this if you set text in the xml
    root.addView(test); // Bang!

Here's also main.xml in my test setup:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/root"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
>
    <EditText android:id="@+id/test"
        android:text="Absolutely meaningless and mostly harmless text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>
Community
  • 1
  • 1
Jarno Argillander
  • 5,885
  • 2
  • 31
  • 33