Reputation: 71
I am a beginner in android development and i can't find a solution to this problem. I want do do something when the screen is pressed, no matter where.
My code:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
RelativeLayout layout = (RelativeLayout) findViewById(R.id.layout);
layout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</RelativeLayout>
Then app crashes exactly when the activity is created. If i remove the listener part it works as it should. Thank you very much.
Upvotes: 0
Views: 199
Reputation: 140
You need to ensure you call setContentView method with R.layout.your_file_name before your findViewById call
Upvotes: 0
Reputation: 44571
You haven't inflated your layout. You need something like
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.yourLayout); // this guy here
RelativeLayout layout = (RelativeLayout) findViewById(R.id.layout);
layout.setOnClickListener(new View.OnClickListener() {
Your RelativeLayout
lives inside of your layout file and since you haven't inflated it with setContentView()
, findViewById()
returns null. This causes a NPE
when you try to set the listener on it.
Upvotes: 3