Android应用程序 - 如何显示项目列表并使其可单击

Gee*_*Out 10 android

我需要在屏幕上显示一个文本项列表,并使它们可以点击.所以它就像是Web应用程序上的链接列表.

如何在Android活动屏幕中执行此操作?

我必须从数据库中提取一些随机数量的项目并将所有项目显示为链接.

知道如何做到这一点?

Ben*_*fez 10

您应该阅读有关ListActivity,ListView的文档并遵循Hello ListView教程.


hum*_*oid 9

是的,你可以做到.创建一个DataExchange类以从Db中获取它.将字符串存储在一个数组中.

创建一个ArrayAdapter以显示从数据库中获取的字符串数组.

例如

public class AndroidListViewActivity extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // storing string resources into Array
    String[] numbers = {"one","two","three","four"}
     // here you store the array of string you got from the database

    // Binding Array to ListAdapter
    this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label,       numbers));
    // refer the ArrayAdapter Document in developer.android.com
    ListView lv = getListView();

    // listening to single list item on click
    lv.setOnItemClickListener(new OnItemClickListener() {
      public void onItemClick(AdapterView<?> parent, View view,
          int position, long id) {

          // selected item 
          String num = ((TextView) view).getText().toString();

          // Launching new Activity on selecting single List Item
          Intent i = new Intent(getApplicationContext(), SingleListItem.class);
          // sending data to new activity
          i.putExtra("number", num);
          startActivity(i);

      }
    });
}
}
Run Code Online (Sandbox Code Playgroud)

显示您单击的特定项目的secondActivity应该是

public class SingleListItem extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.single_list_item_view);

    TextView txtProduct = (TextView) findViewById(R.id.product_label);

    Intent i = getIntent();
    // getting attached intent data
    String product = i.getStringExtra("number");
    // displaying selected product name
    txtProduct.setText(product);

}
}
Run Code Online (Sandbox Code Playgroud)

你必须相应地创建各种布局文件..希望这可以帮助你:)