I want to show a list of three separate textviews in my linear layout. I’m aware that this can be done from the XML file itself , but I want to generate these textviews dynamically.
XML file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:id = "@+id/ll1">
</LinearLayout>
Java file:
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class RegistrationActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle saved){
LinearLayout ll = findViewById(R.id.ll1);
super.onCreate(saved);
setContentView(R.layout.activity_reg);
List<String> names = new ArrayList<>(Arrays.asList("Negotiation","Pyschology","Joke"));
for (int i = 0; i<3;++i){
TextView dynamic = new TextView(this);
dynamic.setText(names.get(i));
dynamic.setTextSize(14);
dynamic.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(RegistrationActivity.this, MainActivity.class));
}
});
ll.addView(dynamic);
}
}
}
The result is a blank page and what I want is three clickable textviews as the result. Where did I go wrong?
2
Answers
May be you forgot to add textview in parentview like this.
If I am not wrong sir you want to add Text view Programmatically
Find you need a layout parent layout Your parent layout is Linear layout set id of a linear layout Suppose id is linerlayout_parent After this in Activity
Now Here Create text view Programatically
if you need three than in Loop paste this code
Kindly set orientation of a Linear layout Vertical