1
votes

méthode onClick introuvable

Je suis nouveau dans ce domaine et je crée une application pour un projet universitaire et je voulais mettre un VideoView dans mon application, j'ai donc regardé cette vidéo (" https://www.youtube.com/watch?v=SrPHLj_q_OQ&t=421s ") et l'a fait et a fonctionné. Mais ensuite, j'ajoute pour copier le code de content_main.xml dans un fragment et cela a cessé de fonctionner et de donner une erreur sur le "android: onClick" sur le bouton. Et quand j'appuie sur CTRL + F1 pour inspecter, il dit ceci:

package intro.android.migueloliveiraapp;


import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.net.Uri;
import android.widget.Button;
import android.widget.VideoView;



/**
 * A simple {@link Fragment} subclass.
 */
public class InicioFragment extends Fragment {


    public InicioFragment() {
        // Required empty public constructor
    }



    @Override
    public View onCreateView (LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_inicio, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        clk = (Button) view.findViewById(R.id.button);
        videov = (VideoView) view.findViewById(R.id.videoView);

        // bind the views here.
        Button button2 = view.findViewById(R.id.button);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // do something here.

            }
        });
    }

    Button clk;
    VideoView videov;


    public void videoplay(View v){
        String videopath = "android.resource://intro.android.migueloliveiraapp/" + R.raw.oliveira;
        Uri uri = Uri.parse(videopath);
        videov.setVideoURI(uri);
        videov.start();
    }



}

Voici mon xml:

package intro.android.migueloliveiraapp;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


/**
 * A simple {@link Fragment} subclass.
 */
public class InicioFragment extends Fragment {


    public InicioFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_inicio, container, false);
    }

}

Voici mon java: p >

package intro.android.migueloliveiraapp;

import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.Toast;
import android.widget.VideoView;


public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        clk = (Button) findViewById(R.id.button2);
        videov = (VideoView) findViewById(R.id.videoView);



        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        //Carregar o layout do fragent incial "InicioFragment"
        InicioFragment inicioFragment = new InicioFragment();
        FragmentManager manager = getSupportFragmentManager();
        manager.beginTransaction()
                .replace(R.id.relative_layout_para_o_fragment, inicioFragment, inicioFragment.getTag())
                .commit();


    }



    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_oliveira) {
            Quem_Oliveira quem_oliveiraFragment = new Quem_Oliveira();
            FragmentManager manager = getSupportFragmentManager();
            manager.beginTransaction()
                    .replace(R.id.relative_layout_para_o_fragment,
                            quem_oliveiraFragment, quem_oliveiraFragment.getTag())
                    .commit();
            Toast.makeText(this, "Oliveira", Toast.LENGTH_SHORT).show();
        } else if (id == R.id.nav_profissao) {
            Profissao profissaoFragment = new Profissao();
            FragmentManager manager = getSupportFragmentManager();
            manager.beginTransaction()
                    .replace(R.id.relative_layout_para_o_fragment,
                            profissaoFragment, profissaoFragment.getTag())
                    .commit();
            Toast.makeText(this, "Profissão", Toast.LENGTH_SHORT).show();
        } else if (id == R.id.nav_feitos) {
            Principais_feitos principais_feitosFragment = new Principais_feitos();
            FragmentManager manager = getSupportFragmentManager();
            manager.beginTransaction()
                    .replace(R.id.relative_layout_para_o_fragment,
                            principais_feitosFragment, principais_feitosFragment.getTag())
                    .commit();
            Toast.makeText(this, "Principais Feitos", Toast.LENGTH_SHORT).show();
        } else if (id == R.id.nav_academicas) {
            Habilitacoes_Academicas habilitacoes_academicasFragment = new Habilitacoes_Academicas();
            FragmentManager manager = getSupportFragmentManager();
            manager.beginTransaction()
                    .replace(R.id.relative_layout_para_o_fragment,
                            habilitacoes_academicasFragment, habilitacoes_academicasFragment.getTag())
                    .commit();
            Toast.makeText(this, "Habilitações Académicas", Toast.LENGTH_SHORT).show();
        } else if (id == R.id.nav_galeria) {
            Galeria galeriaFragment = new Galeria();
            FragmentManager manager = getSupportFragmentManager();
            manager.beginTransaction()
                    .replace(R.id.relative_layout_para_o_fragment,
                            galeriaFragment, galeriaFragment.getTag())
                    .commit();
            Toast.makeText(this, "Galeria", Toast.LENGTH_SHORT).show();
        } else if (id == R.id.nav_contactos) {
            Contactos contactosFragment = new Contactos();
            FragmentManager manager = getSupportFragmentManager();
            manager.beginTransaction()
                    .replace(R.id.relative_layout_para_o_fragment,
                            contactosFragment, contactosFragment.getTag())
                    .commit();
            Toast.makeText(this, "Contactos", Toast.LENGTH_SHORT).show();

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    //video view
    Button clk;
    VideoView videov;

    public void videoplay(View v){
        String videopath = "android.resource://intro.android.migueloliveiraapp/" + R.raw.oliveira;
        Uri uri = Uri.parse(videopath);
        videov.setVideoURI(uri);
        videov.start();
    }


}

Voici mon java InicioFragment:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="16dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="16dp"
    android:background="#003e6f"
    android:orientation="vertical"
    tools:context=".InicioFragment">


    <VideoView
        android:id="@+id/videoView"
        android:layout_width="match_parent"
        android:layout_gravity="center_horizontal"
        android:layout_height="197dp" />

    <Button
        android:id="@+id/button2"
        style="@style/Widget.AppCompat.Button.Borderless"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:background="#FF6600"
        android:text="Play"
        android:onClick="videoplay"
        android:textColor="#ffffff" />

    <ImageView
        android:id="@+id/imagem2"
        android:layout_width="match_parent"
        android:layout_height="360dp"
        android:layout_alignParentBottom="true"
        android:adjustViewBounds="false"
        android:background="@drawable/tech3" />

</LinearLayout>

voici mon InicioFragment.java mis à jour :

"Corresponding method handler'public void videoplay(android.view.View)' not found
Inspection info:The onClick attribute value should be the name of a method in this View's context to invoke when the view is clicked.This name must correspond to a public method that takes exactly one parameter of type View.

Must be a string value, using '\;' to escape characters such as '\n' or '\uxxxx' for a unicode character.

Issue id:OnClick "


0 commentaires

5 Réponses :


0
votes

Vous pouvez l'utiliser pour cliquer.

mPlayVideo = findViewById(R.id.button2);
mPlayVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "Clicked", Toast.LENGTH_SHORT).show();
            }
        });

// Dans oncreate

Button mPlayVideo;


0 commentaires

0
votes

Dans votre xml, vos outils: context = ". InicioFragment fait référence à votre fragment et non à votre activité.

Votre méthode se trouve dans l'activité et non dans la classe de fragment et c'est pourquoi obtenir cette erreur.

Vous pouvez vérifier Appeler une méthode d'activité à partir d'un fragment

Mais je peux vous recommander d'utiliser l'attribut onClick dans vos activités et à l'intérieur du fragment d'utiliser l'écouteur de clic normal:

View view =  findViewById(R.id.viewId);
view .setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
    //do something
  }
});


0 commentaires

0
votes

Faites attention à votre fichier xml que le contexte de ce fichier est votre InicioFragment (tools: context = ". InicioFragment") Par conséquent, la lecture vidéo (View v) doit être dans votre classe InicioFragment. C'est la raison pour laquelle on ne trouve pas. Il ne cherchera pas sur votre MainActivity.

clk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               Log.d("TESTING", "Clicked");
            }
        });

Puisque vous avez également une variable pour votre bouton, une autre option est de faire:

public class InicioFragment extends Fragment {


    public InicioFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.testclassfragment, container, false);
        Button clk = (Button) view.findViewById(R.id.button);
        VideoView videov = (VideoView) view.findViewById(R.id.videoView);
        return view;
    }

    public void videoplay(View v){
        String videopath = "android.resource://intro.android.migueloliveiraapp/" + R.raw.oliveira;
        Uri uri = Uri.parse(videopath);
        videov.setVideoURI(uri);
        videov.start();
    }
}

p >


4 commentaires

J'ai mis à jour la question avec mon java InicioFragment. Si vous pouviez essayer de mettre la méthode là-bas, car cela me donne une erreur sur "findViewById" lorsque je la copie de MainActivity vers InicioFragment.


sur mon MainActivity j'ai "clk = (Button) findViewById (R.id.button); videov = (VideoView) findViewById (R.id.videoView);" dans "protected void onCreate (Bundle savedInstanceState)" est-ce que je ne dois pas le mettre aussi dans InicioFragment? et quand j'essaye de le mettre ça me donne l'erreur dont je parlais sur "findViewByid"


Oui, vous avez raison, clk et videov doivent être sur votre fragment. J'ai mis à jour ma réponse, regardez comment cela se fait sur un fragment. C'est un peu un truc en effet


J'ai mis la méthode de lecture vidéo dans InicioFragment, et elle ne me donne aucune erreur, mais elle dit "La méthode de lecture vidéo n'est jamais utilisée", savez-vous pourquoi?



0
votes

C'est parce que vous avez créé la méthode videoplay () dans votre MainActivity.java . Vous devez mettre votre méthode vidéoplay () dans le InicioFragment.java car il s'agit du fichier correspondant à la mise en page xml que vous avez mentionnée ci-dessus. Initialisez vos variables comme ci-dessous dans votre méthode onCreateView sur InicioFragment

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_inicio, container, false);

        Button btn1 = view.findViewById(R.id.button_id);
        .....
             .....

        return view;
    }

    public void videoplay(View v){
          .........
          .....
    }


1 commentaires

J'ai mis à jour la question avec mon java InicioFragment. Si vous pouviez essayer de mettre la méthode là-bas, car cela me donne une erreur sur "findViewById" lorsque je la copie de MainActivity vers InicioFragment.



0
votes

L'erreur suivante:

public class InicioFragment extends Fragment {

    public InicioFragment() {}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_inicio, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // bind the views here.
        Button button2 = view.findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               // do something here.
            }
        });
    }
}

signifie que vous oubliez d'ajouter la méthode correspondante dans votre classe d'activité lorsque vous utilisez l'attribut android: onClick = "videoplay" . Vous devez donc ajouter la méthode suivante à votre activité:

public void videoplay(View v){
  // do something here.
}

La partie la plus importante est, la balise android: onClick est uniquement fonctionne lorsque vous l'utilisez dans la présentation de contenu de Activity. . Ainsi, android: onClick ne fonctionne pas lorsque vous l'utilisez dans la mise en page du fragment. Vous devez utiliser le onClickListener à la place.

Vous devez lier la vue et ajouter le onClickListener avec quelque chose comme ceci:

"Corresponding method handler'public void videoplay(android.view.View)' not found
Inspection info:The onClick attribute value should be the name of a method in this View's context to invoke when the view is clicked.This name must correspond to a public method that takes exactly one parameter of type View.

Must be a string value, using '\;' to escape characters such as '\n' or '\uxxxx' for a unicode character.

Issue id:OnClick "


0 commentaires