The button and two TextViews will not show up when I navigate to the second activity. They do show up in Design view.
I’ve looked at similar articles but cannot figure out the issue.
I’m using Java.
Thank you
Main.java
package com.example.cybersecgame;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.content.Intent;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, SecondActivity.class));
}
});
}
}
SecondActivity.java
package com.example.cybersecgame;
import static com.example.cybersecgame.R.layout.activity_second;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_second);
}
}
2
Answers
I don’t understand the use of this line
remove it,
and when setting the content make sure you use R.layout.’layout name’, as R.layoout…. refers to you reading the layout file from the drawable layout folder
so it shall be like so
First of all
setContentView(activity_second)
is wrong andsetContentView(R.layout.activity_second)
is the correct one.Also
setContentView(R.layout.activity_second)
is not enough to load theButton
and theTextView
. You have to initialize them inside theonCreate
method usingfindViewById(R.id.text_view)
.The TextView IDs in the code are an example. You should use your own IDs which are defined in layout
activity_second.xml
.