Start Activity from ListView item click Android example

How start certain Activity if user clicked to ListView item
Start Activity from list – launches other activities from list – latest variant!!!!

public class Main extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        try {
        setContentView(R.layout.main);
 
			ListView mlistView = (ListView) findViewById(R.id.idListView);
			mlistView.setAdapter(new ArrayAdapter<String>(this,
			        android.R.layout.simple_list_item_1, 
			        new String[] {"Game", "Help", "Home site"}));
 
        mlistView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
              // When clicked, show a toast with the TextView text Game, Help, Home
              Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
                  Toast.LENGTH_SHORT).show();
              String sText = ((TextView) view).getText().toString();
              Intent intent = null;
              if(sText.equals("Game"))
              intent = new Intent(getBaseContext(),
						Game.class);
              //else if(sText.equals("Help")) ..........
 
              if(intent != null)
				startActivity(intent);              
            }
          });
        } catch (Exception e) {
        	// TODO Auto-generated catch block
        	e.printStackTrace();
        }
 
    }
}

Game class Game.java game.xml
You have to add class Game to AndroidManifest.xml

        <activity android:name=".Game" android:label="GameLabel">
        </activity>

 
package cz.okhelp.listview;
 
import android.app.Activity;
import android.os.Bundle;
 
public class Game extends Activity{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        // you have to create game.xml 
        setContentView(R.layout.game);
    }
}
This entry was posted in Android Examples Code and tagged , , , , , , . Bookmark the permalink.


Comments are closed.

50,863 views