我正在学校开展一个项目,我需要帮助正确实施ListViews
。我必须对项目进行设置和帮助部分,截至目前,我可以显示列表中的内容,并在单击时显示所选项目的Toast
条消息。我的问题是,如何创建和显示特定项目内的内容?例如,我有一个选项"Edit Password"
,当我点击它时,它应显示我的"Edit Password"
屏幕。这适用于我的两个部分。
这是我到目前为止所拥有的。它基本上是android ListView
教程,但我在那里添加了我的选项。我的问题是,当我点击列表中的一个选项时,如何显示其具体细节?就像我之前说的那样,如果我点击"Edit Password"
,我希望它转到"Edit Password"
屏幕。或者在帮助中,如果我点击“Credits”,我希望它直接转到Credits页面。
public class Settings extends ListActivity {
/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this, R.layout.settings, SETTINGS));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id)
{
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
}
});
}
static final String[] SETTINGS = new String[]
{"Set Refresh Rate", "Edit Password", "Delete Account"};
}
答案 0 :(得分:1)
当你扩展ListActivity
时,你已经实现了OnItemClickListener
,你应该覆盖方法onListItemClick
。在该方法中,您应该使用Intent
转到新的Activity
,在那里您将显示所需的内容:
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Intent i = new Intent(this, SecondActivityName.class);
i.putExtra("pos", position); //pass the position of the clicked row so we know what to show.
startActivity(i); // let's go to the other activity
}
SeconActivityName
是您应该创建的Activity
,您可以在哪里展示您想要的其他屏幕(请记住将活动添加到清单文件中!):
public class SecondActivityName extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i = getIntent();
int rowPosition = i.getIntExtra("pos", -1); //we now have the row's position that was clicked in the other activity.
// based on that you show the screen you want for example after a switch
switch (rowPosition) {
case -1:
//this is the default value, something has gone terrible wrong
//finish the activity and hide:
finish();
break;
case 0:
//row 0 was clicked so show the "Set Refresh Rate" screen
setContentView(R.layout.refresh_rate__screen);
break;
//do the same for the other rows;
//...
如果各种设置的屏幕没有那么不同,这将有效。如果他们是你可能必须为每个活动实施不同的活动,并根据位置参数在onListItemClick
开始相应的活动。