M
maystorm
Neues Mitglied
- 2
Hallo Leuts,
ich zermartere mir seit Stunden den Kopf, warum bei mir die Methode findViewById() nicht funktioniert. Hier ein Beispiel, das einen Button in der main.xml definiert. Diesen Button will ich mit findViewById() referenzieren, bekomme aber immer null zurück (was ich mit einem Toast sichtbar mache):
main.xml:
strings.xml:
Manifest.xml:
Ich bitte um Erleuchtung, da ich absolut nicht weiß, was falsch sein soll.
TIA!
ich zermartere mir seit Stunden den Kopf, warum bei mir die Methode findViewById() nicht funktioniert. Hier ein Beispiel, das einen Button in der main.xml definiert. Diesen Button will ich mit findViewById() referenzieren, bekomme aber immer null zurück (was ich mit einem Toast sichtbar mache):
Code:
// StartActivity.java
package no.package_name;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;
public class StartActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button button = (Button) findViewById(R.id.a_normal_button);
final String msg = (button == null ? "Button reference is null!" : "Button was found");
final Toast toast = Toast.makeText(this, msg, Toast.LENGTH_LONG);
toast.show();
}
}
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:label="@+id/a_normal_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_text"
/>
</LinearLayout>
Code:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">A test of the findViewById() method</string>
<string name="app_name">FindViewByIdTest</string>
<string name="button_text">I am a normal button!</string>
</resources>
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="no.package_name"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".StartActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
TIA!
Zuletzt bearbeitet: