I'm completely new to Android and am trying to add a simple button to my view, but my view is completely blank. Here is my setup:
EDIT: I have now changed my code to write this programmatically since I'm used to that with iOS.
I'm now getting the following error:
Error: Attempt to invoke virtual method 'void android.widget.LinearLayout.setOrientation(int)' on a null object reference
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
LinearLayout linearLayout;
public Button myButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
// Create main view
linearLayout = (LinearLayout) findViewById(R.id.linearLayout1);
linearLayout.setOrientation(LinearLayout.VERTICAL);
// Create button
myButton = new Button(this);
myButton.setText("Fire Call");
// Add button to view
linearLayout.addView(myButton);
}
}
You need to setContentView which takes a View or a layout resource id.
Also, you can only call findViewById if you provide a layout resource id, and call setContentView with it. Alternatively, you could inflate it and call view.findViewById on the resulting inflated view.
Here's your code with some changes that should hopefully fix your new issue:
public class MainActivity extends Activity {
LinearLayout linearLayout;
public Button myButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
// Create main view
linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
// Create button
myButton = new Button(this);
myButton.setText("Fire Call");
// Add button to view
linearLayout.addView(myButton);
setContentView(linearLayout);
}
}
I cannot pinpoint the error but maybe you can.
Try checking after every line you type and see if the button appears. Also check if the problem is with button only or does it extend to other layouts as well.
Just type and see what happens.
Follow it up with dimensions.
Don not forget to save after each step. Usually all such problems can be solved by detailed debugging.
If none of the layout appears, try and restart the software.
You didn't callsetContentView(R.layout.activity_main) , in your code there, you commented it out, so your layout wasnt inflated so you got a blank white screen. Uncomment that line and you will be fine.
Related
The problem is MainActivity starts with a setContentView with a layout.xml. We can add buttons or anything to the layout and code in in the MainActivity class but when I try to code the buttons of another layout in the same Activity the app forces stop . Whats wrong ?
Ok I found out that is because of the context.
When you try to change other activity you have to use layoutinflater. Example below
LayoutInflater inflater = getLayoutInflater();
View myLayout = inflater.inflate(R.layout.my_layout, null);
To work with widgets inside it like buttons or anything .
Button b = mylayout.findViewById(R.id.button);
b.setText("Successfully changed");
Now you can use myLayout as your changed layout.
Please sent me your Activities
What the text of problem ?
You may write next code to go to another activity
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),nameActivity.class));
}
});
Where button is name of your button
See that you xml-file doesnt have any mistakes
You are getting a crash because you are trying to access the layout when it is not inflated. In other words, you must call setContentView() on an Activity, or inflater.inflate() on a Fragment to instantiate the view and make the elements accessible for manipulation. So if you want to add buttons to another Activity, you would need to call its onCreate() and setContentView() before you can add buttons to it.
EDIT: In response to comments...
In order to access/manipulate/modify elements in a layout at runtime, they must first be instantiated, which happens when the view is inflated. So to add a button to an Activity at runtime, you would do it in the onCreate() method after calling setContentView() like this:
Keep in mind this is the onCreate() of your SECOND activity...not your main Activity. So your main activity would start this Activity, then the button would get created during the setup of the second Activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_second_activity;
Button button = new Button(this);
button.setText("Your New Button");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("NEW BUTTON", "I just clicked my new button!");
}
});
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.layout_in_your_second_activity);
relativeLayout.addView(button);
}
If you are using a Fragment to display your UI, you can't access your UI elements until you have inflated your layout, which happens in the onCreateView() method. So you would do something like this in your Fragment code:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.your_fragment_layout, container, false);
RelativeLayout relativeLayout = (RelativeLayout) view.findViewById(R.id.container_layout_that_holds_button);
//You would get your context from an onAttach() Override
Button button = new Button(context);
button.setText("Your New Button");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("NEW BUTTON", "I just clicked my new button!");
}
});
relativeLayout.addView(button);
return view;
}
You're likely getting a NullPointerException when you try to manipulate your layouts before they are created. Keep in mind that even if you have an XML file with layouts specified within, the actual objects for those elements won't be created until the system decides it needs them, which happens when you actually try to display the view.
I have created an LinearLayout object in my .java file and tried to connect it with my .xml layout by using the following code,but it is not responding. Can you please explain to me why and what errors are in this code? I have named the id of the LinearLayout of .xml file as "root".
public class MainActivity extends Activity {
LinearLayout l;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ImageView HelloWorldImageView = new ImageView(this);
TextView t=new TextView(this);
t.setText("hello");
HelloWorldImageView.setImageResource(R.drawable.ic_launcher);
l=new LinearLayout(this);
l=(LinearLayout)findViewById(R.id.root);
l.addView(t);
l.addView(HelloWorldImageView);
setContentView(l);
}
}
Do it like this-
setContentView(R.layout.yourxml);
ImageView HelloWorldImageView = new ImageView(this);
TextView t=new TextView(this);
t.setText("hello");
HelloWorldImageView.setImageResource(R.drawable.ic_launcher);
l=(LinearLayout)findViewById(R.id.root);
l.addView(t);
l.addView(HelloWorldImageView);
You have to set that xml file in the setContentView() which has the root linear layout in it.
First off- you don't need the new LinearLayout line. The findViewById() will return an instantiated version. Same for the the other newed Views.
Secondly- you want to do a setContentView() before making any calls to findViewById(). This way you set the layout (by passing it a layout id), Android will instantiate all the Views in your layout, and you can get references to them via findViewById().
after I asked if I should use XML or a View class for my project you told me, that I should do everything possible in XML and use a class for the rest. You told me, that animating Sprites isn't possible with XML so I wanted to make a View Class. I got the tip to google "LayoutInflater" for this and I did.
There aren't many Informations about inflaters so I visited android's developers database and tried to find out how this works.
As far as I know now, you have to put something into the onCreate method of your main game activity (the setContentView has to be the mainXML).
So now I created a LinearLayout in my mainXML and called it "container" and made this being a ViewGroup called "parent".
Now I have created a global variable "private View view" and wrote this line:
view = LayoutInflater.from(getBaseContext()).inflate(new ViewClass(this),
null);
Thw Problem now is that u can't inflate a class like this and I think I'm doing this whole inflating thing wrong.
Do you have any tips and tricks for me for making it work to have a LinearLayout in my mainXML and being able to make the content from my View Class appear in it?
EDIT:
Got it to work without errors, but nothing happens if I start my game now.
Here is the code pls answer if u have any solutions:
super.onCreate(savedInstanceState);
// inflate mainXML->
View mainView = getLayoutInflater().inflate(R.layout.activity_game, null);
// find container->
LinearLayout container = (LinearLayout) mainView.findViewById(R.id.container);
// initialize your custom view->
view = new GameLayout(this);
// add your custom view to container->
container.addView(view);
setContentView(R.layout.activity_game);
And my GameLayout:
public GameLayout(Context context)
{
super(context);
}
#Override
protected void onDraw(Canvas canvas)
{
canvas.drawColor(Color.BLACK);
}
There are two ways of going about this. I'll show you one of them. Do the following in your onCreate(Bundle) before calling setContentView(...):
// inflate mainXML
View mainView = getLayoutInflater().inflate(R.layout.mainXML, null);
// find container
LinearLayout container = (LinearLayout) mainView.findViewById(R.id.container);
// initialize your custom view
view = new ViewClass(this);
// add your custom view to container
container.addView(view);
Finally:
setContentView(mainView);
Alternatively, you can place your custom view inside mainXML:
<your.package.name.ViewClass
android:id="#+id/myCustomView"
android:layout_width="match_parent"
android:layout_height="match_parent"
.... />
I am working on the Android guide here: http://developer.android.com/training/basics/activity-lifecycle/starting.html and there is reference to a variable that has never been created
mTextView = (TextView) findViewById(R.id.text_message);
Where am I supposed to define text_message?
Thanks for your help!
Update: I believe the chunk of code from which this is taken is merely an example, and not to be incorporated with the application we created in the previous part of the tutorial.
It is declared here
TextView mTextView; // Member variable for text view in the layout // Right here
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Declaring it outside of a method, generally right after class declaration, makes it a member variable so it can be used anywhere in the class, including inner classes and listeners. You just can't initialize it in the same place because you haven't inflated your Layout yet by calling setContentView()
Short example
public class MyActivity extends Activity
{
TextView mTextView; // Member variable for text view in the layout
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the user interface layout for this Activity
// The layout file is defined in the project res/layout/main_activity.xml file
setContentView(R.layout.main_activity);
// Initialize member TextView so we can manipulate it later
mTextView = (TextView) findViewById(R.id.text_message); // findViewById) looks for the id you set in the xml file, here text_message
}
R.id.text_message is defined in the main_activity.xml which could look something like this
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/text_message" <!-- this is where the R.id.text_message comes from -->
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"/>
</LinearLayout>
That documentation is definitely good to go through but you may want to start Here and go through a short example starting from creating a project
use this way define the xml layout inside the folder of res/layout/main.xml and set in setconentView.
private TextView mTextView = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
stContentView(R.layout.main);
mTextView = (TextView) findViewById(R.id.text_message);
mTextView.setText("Hello");
}
i have an activity that displays two buttons , on click of call button i want to show another activity as shown in image.
Please help .How to achieve this
One way to do it is to have a custom layout which you add to each activity with a viewgroup as such:
private View view;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ViewGroup parent = (ViewGroup) findViewById(R.id.linearLayout1);
view = LayoutInflater.from(getBaseContext()).inflate(R.layout.custom_layout,
null);
parent.addView(view);
Then you just need to implement your listeners and whatnot further down :)
You need to create xml file of these two buttons and add that new xml into old one by using Layout Inflator. for e.g
1) your new xml
LayoutInflator buttons = LayoutInflater.from(getBaseContext()).inflate(R.layout.buttons,
currentxml, false);
2) your old xml parent referenced through id -->
RelativeLayout relativeLayout = (RelatveLayout) findViewById(R.id.oldxml);
3) now add..
relativeLayout.addView(buttons);
You can Use Pop up By Adding this in your function. Popuser is a xml file which you want to inflate.
public void popupshow(){
try{
LayoutInflater inflater=(LayoutInflater)SRSDMain.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Display display=getWindowManager().getDefaultDisplay();
int width=display.getWidth()/2;
int height=display.getHeight()/2;
View pop=inflater.inflate(R.layout.popupuser,null,false);
pop.measure(View.MeasureSpec.UNSPECIFIED,View.MeasureSpec.UNSPECIFIED);
height=pop.getMeasuredHeight();
width=pop.getMeasuredWidth()+50;
pu=new PopupWindow(pop,width,height,true);
pu.showAtLocation(findViewById(R.id.ll3),Gravity.CENTER,1,1);
Button btn=(Button)pu.getContentView().findViewById(R.id.button);
btn.getBackground().setColorFilter(new LightingColorFilter(0xFF505450,0xFF101010));
btn.setTextColor(Color.WHITE);
btn.setTypeface(null,Typeface.BOLD);
btn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
//anything you want to do
pu.dismiss();
}
});
}
catch(Exception ex){
//Catch The Exception
}
}
}