Android: findViewById Layout retourne null

Résolu
yoanpg Messages postés 156 Date d'inscription dimanche 15 février 2009 Statut Membre Dernière intervention 20 janvier 2024 - 24 août 2020 à 11:44
yoanpg Messages postés 156 Date d'inscription dimanche 15 février 2009 Statut Membre Dernière intervention 20 janvier 2024 - 28 août 2020 à 08:59
Bonjour à tous, :)

Je travaille sur une application Android.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main_layout"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.google.android.gms.samples.vision.ocrreader.MainActivity"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/ocr_header"
        android:id="@+id/status_message"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_centerHorizontal="true" />
</LinearLayout>


MainActivity.java
public class MainActivity extends Activity implements View.OnClickListener {

    // Use a compound button so either checkbox or switch widgets work.
    private LinearLayout mainLayout;
    private CompoundButton autoFocus;
    private TextView textValue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mainLayout = (LinearLayout) findViewById(R.id.activity_main_layout);

        statusMessage = (TextView)findViewById(R.id.status_message);
    }
}


statusMessage est bien lié à mon TextView (ainsi que d'autre éléments boutons et checkbox non décrits ici). Cependant, mon mainLayout est toujours null

D'après mes recherches, c'est parce qu'il faut d'abords inflate le layout. Mais setContentView() est sensé faire l'inflate.

J'ai le même code que l'exemple https://stackoverflow.com/questions/3477422/what-does-layoutinflater-in-android-do (voir réponse avec le titre "What does LayoutInflator do?"), et pourtant j'ai toujours null retourné.

Pourquoi ? Comment faire pour lier mon layout?
Merci d'avance de votre aide :)

1 réponse

yoanpg Messages postés 156 Date d'inscription dimanche 15 février 2009 Statut Membre Dernière intervention 20 janvier 2024 3
28 août 2020 à 08:59
J'ai fini par trouver le problème.
En fait j'ai plusieurs xml: activity_main.xml et activity_main-v17.xml et je ne modifiais pas la bonne
0
Rejoignez-nous