Advertisement

header ads

How to add TextView widgets dynamically to existing layout resource - Android tutorial



This Project Demonstrates how to add TextView widget dynamically to existing layout resource. It is also demonstrate various methods of TextView including .setText(), .setTextColor(), .setTextSize(), .setGravity(), .setBackgroudColor().


And also we need to use these methods inside the project.

RGB Color::
myText.setTextColor(Color.rgb(10,11,12)); // RGB means RED, GREEN, BLUE

For Background Color:
myText.setBackgroundColor(Color,rgb(10,11,12));

We don't need any permission required in AndroidManifest.xml. And also don't need to use android_main.xml.

Here is the Code


@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        LinearLayout layout = new LinearLayout(this);

        final TextView myText = new TextView(this);
        myText.setText("\nWelcome to \n" + getResources().getString(R.string.app_name));

        myText.setTextColor(Color.RED);

        final EditText simple_etFontSize = new EditText(this);
        simple_etFontSize.setHint("Enter Font Size...");
        simple_etFontSize.setInputType(InputType.TYPE_CLASS_NUMBER);

        Button simple_show = new Button(this);
        simple_show.setText("Apply Font Size to Text");

        simple_show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ((simple_etFontSize.getText().toString()).equals("")) {
                    Toast.makeText(getApplicationContext(), "Enter Number ..", Toast.LENGTH_LONG).show();
                } else {
                    myText.setTextSize(Integer.parseInt(simple_etFontSize.getText().toString()));
                    myText.setGravity(Gravity.CENTER);
                }
            }
        });

        layout.addView(simple_etFontSize);
        layout.addView(simple_show);
        layout.addView(myText);

        setContentView(layout);
    }


Run this Code in your Android device or Virtual Device and test it.

Post a Comment

0 Comments