Não consigo consertar o seguinte código:
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();
}
}
Aparece as seguintes mensagens de erro:
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.
Quando a gente muda o código como aparece na sugestão, muda onde tem OnItemClickListener
para AdapterView.OnItemClickListener
, depois da erro na linha que chama a função chamaAtividade()
, e obviamente sugere a mudança da linha
listView.setOnClickListener(chamaAtividade());
para
listView.setOnClickListener((View.OnClickListener) chamaAtividade());
Aparentemente era pra dar td certo, mas quando utilizo o celular pra executar o código, nem abre, diz que o aplicativo parou. O que pode ser?
As Activitys 'Activity1' e 'Activity' foram apenas criações de activitys em branco para fazer o teste e o arquivo activity_main.xml possui o seguinte código:
<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>