Wednesday 18 October 2017

6. Adding Views Programatically in Android

6. Adding Views Programmatically in Android



We can add views from xml layout. Also we can do the same thing from java code also. Just create the layout reference with Id or create new layout and add new views to this layout.

Below is the code snapshot for the same.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/mainActivityLinearlayout"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical"
  tools:context="tutorial.android.sachin4droid.androidtutorials.MainActivity">

  <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Hello World123!"
      android:textColor="@color/colorPrimaryDark"
      android:textSize="30dp"
      android:textStyle="bold"
      android:id="@+id/textView" />

</LinearLayout>

MainActivity

public class MainActivity extends AppCompatActivity {
  private static String TAG = "MainActivity";

  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      Log.i(TAG,"onCreate called now!!!");

      LinearLayout linearLayout = (LinearLayout) findViewById(R.id.mainActivityLinearlayout);

      TextView textView2 = new TextView(this);
      textView2.setText("textView2 generated from java code");
      textView2.setTextColor(Color.RED);

      ImageView imageView = new ImageView(this);
      imageView.setImageResource(R.drawable.logo);

      linearLayout.addView(textView2);
      linearLayout.addView(imageView);



  }

  @Override
  protected void onStart() {
      super.onStart();
      Log.i(TAG,"onStart called now!!!");
  }

  @Override
  protected void onResume() {
      super.onResume();
      Log.i(TAG,"onResume called now!!!");
  }

  @Override
  protected void onPause() {
      super.onPause();
      Log.i(TAG,"onPause called now!!!");
  }

  @Override
  protected void onStop() {
      super.onStop();
      Log.i(TAG,"onStop called now!!!");
  }

  @Override
  protected void onDestroy() {
      super.onDestroy();
      Log.i(TAG,"onDestroy called now!!!");
  }
}


    

No comments:

Post a Comment

Extract error records while inserting into db table using JDBCIO apache beam in java

 I was inserting data into postgres db using apache beam pipeline. it works perfectly with JdbcIO write of apache beam library. But, now, i ...