通过单击ListViewItem打开另一个活动并传递文本和图像。

时间:2013-10-16 14:56:27

标签: java android listview

为了让您更容易理解,我正在尝试制作的应用程序向我显示了一系列书籍 - 书名和封面图片。单击时,它将转到另一个活动,其中包括封面的放大图像和书籍的描述。它应该是可滚动的。
这就是我有多少。

MainActivity.java

public class MainActivity extends ListActivity {
TextView select;
String[] items = { "Naruto", "One Piece", "Bleach", "Harry Potter", "Vampire's Assistant",
        "Pet Cemetery" };

/** Called with the activity is first created. */
@Override
public void onCreate(Bundle a) {
    super.onCreate(a);
    setContentView(R.layout.activity_main);
    setListAdapter(new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, items));
    select = (TextView) findViewById(R.id.selection);
}

public void onListItemClick(ListView parent, View v, int position, long id) {
    select.setText(items[position]);
}
}

activity_main.xml中

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:orientation="vertical"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent" >

    <TextView
     android:id="@+id/selection"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"/>

    <ListView
     android:id="@android:id/list"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:drawSelectorOnTop="false"/>
    </LinearLayout>

2 个答案:

答案 0 :(得分:1)

public void onListItemClick(ListView parent, View v, int position, long id) {
    Intent i = new Intent(this, ActivityTwo.class);
    i.putExtra("book_position", position);
    startActivity(i);
}

ActivityTwo(在onCreate或您觉得舒服的任何地方):

Bundle extras = getIntent().getExtras();
if (extras != null && extras.getInt("book_position", 0) > 0) {
   int bookPosition = extras.getInt("book_position");
   // Do something with the position. E.g. retrieve the data from the String array in this position and populate a TextView/ImageView
}

答案 1 :(得分:0)

public void onListItemClick(ListView parent, View v, int position, long id) {
startActivity(new Intent(getBaseContext(), ActivityToStart.class).putExtra("book", items[position]));
}

然后在ActivityToStart

  public class ActivityToStart  {
    private String bookName;
    @Override
      public void onCreate(Bundle bundleSavedInstance) {
        super.onCreate(bundleSavedInstance);
        getIntentExtras();
    }
    public void getIntentExtras(){
      this.bookName = getIntent().getExtra().getString("book");
    }


}