<分区>
我正在使用 Java 和 Android Studio 创建我的第一个 Android 应用。我有一个主类和布局(在适配器的帮助下)显示章节编号的 ListView 。我有一个 clicklistener,当单击一行时,将加载一个新 Activity 。但是,我想做的是捕获一个变量,该变量记录单击了哪一行,以便我可以在新 Activity 中加载相关内容。做这个的最好方式是什么?
主要 Activity :
public class MainActivity extends AppCompatActivity {
String[] nameArray = {"Chapter 1","Chapter 2","Chapter 3","Chapter 4","Chapter 5","Chapter 6", "Chapter 7", "Chapter 8", "Chapter 9", "Chapter 10", "Chapter 11", "Chapter 12", "Chapter 13", "Chapter 14", "Chapter 15", "Chapter 16", "Chapter 17", "Chapter 18", "Chapter 19", "Chapter 20", "Chapter 21" }; //List of chapters to display
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ChapterlistAdapter whatever = new ChapterlistAdapter(this, nameArray);
listView = (ListView) findViewById(R.id.chapterListview);
listView.setAdapter(whatever);
// Make the row respond when clicked
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Log.d("dev","Its clicked" );
goToChapter();
}
});
}
/** Called when the user taps the Send button */
public void goToChapter() {
Intent intent = new Intent(this, CardView.class);
intent.putExtra(EXTRA_MESSAGE, "chapter clicked");
startActivity(intent);
}
章节列表适配器:
public class ChapterlistAdapter extends ArrayAdapter {
//to reference the Activity
private final Activity context; //Stores which activity the list listview is on?
//to store the list of countries
private final String[] chapterArray;
public ChapterlistAdapter(Activity context, String[] nameArrayParam){
super(context,R.layout.chapter_listview_row , nameArrayParam);
this.context=context;
this.chapterArray = nameArrayParam;
}
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View rowView=inflater.inflate(R.layout.chapter_listview_row, null,true);
//this code gets references to objects in the listview_row.xml file
TextView nameTextField = (TextView) rowView.findViewById(R.id.chapterListviewRowText);
//this code sets the values of the objects to values from the arrays
nameTextField.setText(chapterArray[position]);
return rowView;
};
}
我的想法是在 putExtra 方法中传递一个变量——但是我不确定如何捕获该变量。我可以从 MainActivity 获取它吗?还是我必须在适配器类中执行此操作?
最终目标是了解点击了哪个章节,以便显示该章节的内容。