2

I already have an XML layout with some buttons in it, and now i want to add a textview to the same layout, but in my Java class. I don't get any errors until the "addView" line. I would also appreciate it if someone could tell me a better way to add onto a pre-existing XML layout in Java.

public class MyActivity extends Activity{
TextView textview;
RelativeLayout layout;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
layout=(RelativeLayout)findViewById(R.id.mylayout); 
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParam(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
textview=new TextView(this);
textview.setId(16);
textview.setText("Help");
layout.addView(textview, params);
setContentView(layout);
}

1 Answer 1

2

Your code should be like this, since you already have xml layout, you should first setContent to xml layout and then add new view to the Relativelayout.

public class MyActivity extends Activity{

TextView textview;
RelativeLayout layout;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.file_name);
    layout=(RelativeLayout)findViewById(R.id.mylayout); 
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParam(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
    textview=new TextView(this);
    textview.setId(16);
    textview.setText("Help");
    layout.addView(textview, params);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, it works now! also, would you happen to know of a more convenient way to add onto a pre-existing XML layout in Java?
This is the most convenient way you can do it. Because, if there is already a layout file existing then we need to set the view to it. The next step is to get the layout to which we need to add new dynamic elements of UI. So this is pretty much it. If you want to know more dreamincode.net/forums/topic/…
Also, you can go through examples in APIDemos in android sdk. They have few examples adding dynamic views. But the code will be pretty much same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.