-1

I want to add programmatically a TextView in current view. I know how to make it when I create a new layout but I want to add this to current layout, the main problem is how to get reference to main_activity layout.

Thanks for answers.

2 Answers2

1

Let's say that you have a LinearLayout in your project like this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:id="@+id/main"
android:layout_height="wrap_content" 
android:orientation="vertical">
</LinearLayout>

To add many TextView's in your layout, you can do something like this:

public class YourActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        View linearLayout =  findViewById(R.id.main);


        TextView valueTV = new TextView(this);
        valueTV.setText("hallo hallo");
        valueTV.setId(5);
        valueTV.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));

        ((LinearLayout) linearLayout).addView(valueTV);
    }
}
Luiz Fernando Salvaterra
  • 4,192
  • 2
  • 24
  • 42
  • as I understand this code add text view to a new linearLayout. I want to add a textView to this setContentView(R.layout.main); I created main aplication view and inside onCreate I have condition that check variable and if true add an extra textView to current view – Michał Urban Apr 24 '17 at 21:46
  • is the same thing bro, you can find your layout, and add your TextView on it. I edited my answer – Luiz Fernando Salvaterra Apr 24 '17 at 21:47
  • Thank you it works perfectly :) tell me every layout or button etc. inherit after View? Such as in java String, Integer etc. inherit after Object? – Michał Urban Apr 24 '17 at 21:51
  • Yes, with one exception, layout managers like Relative Layout, LinearLayout, FrameLayout inherit from ViewGroup and the ViewGroup class inherit after View :D Can you accept the answer? – Luiz Fernando Salvaterra Apr 24 '17 at 21:55
  • Probably I spoil something. When I want to find layout View linearLayout = findViewById(R.id.activity_main); I don't have access to activity_main, but when I try something like that View linearLayout = findViewById(R.layout.activity_main); it's forbidden action. Shoul I add main_activity code? – Michał Urban Apr 25 '17 at 07:40
-1
private boolean tuVariable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.completar_perfil);
        if(tuVariable){ //si tu variable es true
            TextView textView = new TextView(this);
            textView.setText("you message");
        }
Isa M
  • 159
  • 1
  • 10