我已经实施了ListActivity
,并且希望为列表中每个可能选择的项目启用不同的intent
。
例如:
点击“关于”项目应启动intent
新活动,然后点击“访问电话库”项目,应启动intent
打开手机图库(选择图像说)。
我想了解两件事:
intent
?以下是MyActivity
的代码(实施ListActivity
):
public class MyActivity extends ListActivity implements OnItemClickListener
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.list_activity);
ListView listView = (ListView) findViewById(android.R.id.list);
listEntryClass listEntries[] = new listEntryClass[]
{
new listEntryClass( "About", "About" ),
new listEntryClass( "Access Phone Gallery", "Access Gallery and Choose an Image" )
};
listEntryArrayAdapter adapter = new listEntryArrayAdapter(this, R.layout.list_entry_layout, listEntries);
View header = (View)getLayoutInflater().inflate(R.layout.list_header_layout, null);
TextView headerValue = (TextView) header.findViewById(R.id.list_header);
headerValue.setText( this.getString(R.string.headerPrefs) );
listView.addHeaderView(header);
listView.setAdapter(adapter);
listView.setOnItemClickListener( this );
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Log.d(TAG, "Clicked an entry");
}
}
我想在某个地方点击的项目的switch-case
上应该有id
,但不知道该怎么做。
答案 0 :(得分:1)
@Override
public void onItemClick(AdapterView <? > parent, View view, int position, long id)
{
if (postion == 0) {
startActivity(MyActivity.this, FirstActivity.class);
} else if (possion == 1) {
startActivity(MyActivity.this, SecondActivity.class);
} else {
startActivity(MyActivity.this, ThirdActivity.class);
}
}
答案 1 :(得分:1)
如何确定点击了哪个项目,以便启动正确的意图?
@Override
public void onItemClick(AdapterView <? > parent, View view, int position, long id) {
// Here position denotes which row index you clicked.
//If you clicked first item in ListView then row index will be zero
// and so on...
switch (position) {
case 0:
//First Item/row clicked
break;
case 1:
//Second Item/row clicked
break;
}
}
如何选择列表中的项目更改样式? (比如突出显示以便用户体验更好)
至于设置颜色,您需要StateListDrawable
。您可以使用android:listSelector
属性在列表中设置此项,并在XML中定义drawable,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:state_focused="true"
android:drawable="@drawable/item_disabled" />
<item android:state_pressed="true"
android:drawable="@drawable/item_pressed" />
<item android:state_focused="true"
android:drawable="@drawable/item_focused" />
</selector>
ListView xml如下所示。
<ListView android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:dividerHeight="0dip"
android:divider="@null"
android:listSelector="@drawable/list_selector"
android:layout_gravity="center" />