यह उदाहरण दर्शाता है कि Android में Java कोड से TextView बनाकर LinearLayout में डायनामिकली कैसे जोड़ा जाए।
चरण 1: नया प्रोजेक्ट बनाएं
Android Studio में नया प्रोजेक्ट बनाएं।
चरण 2: लेआउट XML
res/layout/activity_main.xml - खाली LinearLayout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/rlMain"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
android:orientation="vertical" />
चरण 3: MainActivity.java में डायनामिक व्यू बनाएं
src/MainActivity.java:
package app.com.sample;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout llMain = findViewById(R.id.rlMain);
TextView textView = new TextView(this);
textView.setText("I am added dynamically to the view");
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
textView.setLayoutParams(params);
llMain.addView(textView);
}
}
चरण 4: AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
ऐप चलाएं
TextView डायनामिकली LinearLayout में जुड़ा हुआ दिखेगा।
