开发者

Is there a more efficient way to make my ListView? Only been programming with Android for about 2 weeks

开发者 https://www.devze.com 2023-04-01 22:50 出处:网络
I\'m extremely new to programming android and programming in general. Haven\'t learnt anything previous and was just interested in learning some android dev. Anyhow I\'ll paste my code, but I was wond

I'm extremely new to programming android and programming in general. Haven't learnt anything previous and was just interested in learning some android dev. Anyhow I'll paste my code, but I was wondering if there's a better and more efficient way to create what I'm doing, because it took my about 3 days to even work out how to create this as I couldn't find any tutorials on setting intents up with ListView items. Thanks for your help in advance :)

public class main extends ListActivity {

@Override
public void onCreate(Bundle saved开发者_StackOverflowInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


    String[] listitems = new String[] {"1","2","3","4","5"};

    this.setListAdapter(new ArrayAdapter<String>(this, R.layout.rowlayout,
            R.id.label, listitems));
}

//This is mainly the section I'm unsure about :)

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);

            switch (position){
            case 0:
                Intent second = new Intent(this, second.class);
                startActivity(second);
            }
            return;
}

}


The code is technically OK, but your onListItemClick() method implementation is somewhat unusual. A typical pattern when using ListView is to get the item you clicked on, and do something with it, or pass it to another activity. A simple example:

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);

    // get the item we clicked on
    String item = (String) this.getListAdapter().getItem(position);

    Intent second = new Intent(this, second.class);
    // add the clicked item to the intent, to pass it to the second activity
    second.putExtra("com.my.package.listItem", item);
    startActivity(second);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消