import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.RelativeLayout;
public class register_activity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
RelativeLayout RLayout = (RelativeLayout) View.inflate(this, R.layout.register, null);
RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
Button btnCreateNew = new Button(this);
btnCreateNew.setText("Create New User");
btnCreateNew.offsetTopAndBottom(10);
btnCreateNew.offsetLeftAndRight(10);
RLayout.addView(btnCreateNew, p);
}
}
So that code works and runs just fine, only I can not see the button being displayed. The layout is simply blank with nothing inside it.
What is wrong?
You got a NullPointerException, right? (Check your LogCat!)
The reason:
You create a Button as a member variable with
thisas a parameter. That might cause some trouble asthismight not be defined whennew Button(this)is called. Move the initialization intoonCreateYour
RLayoutwill be null, and here I am very sure. The reason is, that you can’t callfindViewById()before you calledsetContentView(). If you call it before, Android has no idea where to look at and returns null.update
As you changed your question quite a bit, here is my updated answer:
You set your content to
R.layout.registerand after that you inflate it again.My solution for you: just use
setContentView(R.layout.register), than usefindViewById(R.id.layout_id)and finally create and add your button:Of course you can also add the button in the xml layout directly. I would prefer this way, because you have a better separation between layout and code.
Basic XML structure (style it to as you want):
The reason for you blank screen was, that you added the button to the new created
RLayoutbut this layout was never part of your screen (never added bysetContentView())