1
I can’t fix the following code:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] atividades = new String[]{"Atividade 1", "Atividade 2"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, atividades);
ListView listView = (ListView) findViewById(R.id.lv);
listView.setAdapter(adapter);
listView.setOnClickListener(chamaAtividade());
}
public OnItemClickListener chamaAtividade() {
return (new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent;
switch (position) {
case 0:
intent = new Intent(getBaseContext(), Activity1.class);
startActivity(intent);
break;
case 1:
intent = new Intent(getBaseContext(), Activity2.class);
startActivity(intent);
break;
}
}
});
}
public void sair(View view) {
finish();
}
}
Appears the following error messages:
Error:(30, 12) error: cannot find Symbol class Onitemclicklistener
Error:(31, 21) error: cannot find Symbol class Onitemclicklistener
Error:Execution failed for task ':app:compileDebugJavaWithJavac'. Compilation failed; see the Compiler error output for Details.
When we change the code as it appears in the suggestion, it changes where it has OnItemClickListener
for AdapterView.OnItemClickListener
, after the error in the line calling the function chamaAtividade()
, and obviously suggests the change of line
listView.setOnClickListener(chamaAtividade());
for
listView.setOnClickListener((View.OnClickListener) chamaAtividade());
Apparently it was to give td right, but when I use the phone to run the code, nor open, says the application stopped. What can be?
Activitys 'Activity1' and 'Activity' were only empty activitys creations to test and the activity_main.xml file has the following code:
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sair"
android:onClick="sair"/>
<ListView
android:id="@+id/lv"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
</ListView>
probably Voce copied the code from somewhere and did not import the right classes.. how are your Imports?
– leofontes
I modified the content by adding the Imports
– Hennan Lewis
Hennan, you are creating an onItemClickListener for an onClickListener. They are different things. Try switching to listview.setOnItemClickListener on onCreate
– Jhonatan Pereira