2014-01-14 83 views
0

我想在Android中构建我的第一个ListView,为此我构建了一个自定义ListAdapter。所以我创建了一个名为NotificationsAdapter的类,它扩展了BaseAdapter。因为我希望能够到字符串翻译成其他语言,我创建了一个字符串数组中的strings.xml:如何将Android字符串数组加载到ListView中?

<string-array name="notifications_string_array"> 
    <item>The first item</item> 
    <item>The second item</item> 
    <item>Number three</item> 
    <item>Numero four</item> 
</string-array> 

下一步dislaying的项目在这份名单中,我也希望能够给每点击项目。这应该创建一个意图,让用户进入下一个屏幕(总是相同的),我必须给它一个putextra,以便在下一个活动中知道用户点击了哪个项目。此外,我想在列表项旁边放置一个自定义图标。

在我的适配器我已经得到了我在其中加载notifications_string_array如下构造:

int theStringArray = R.array.notifications_string_array; 

然而这是字符串数组的只是ID。 所以第一个问题;我如何加载整个数组?

然后我需要加载在视图中的数组,我尝试做像这样:

@Override 
public View getView(final int position, View convertView, ViewGroup viewGroup) { 
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    View rowView = inflater.inflate(R.layout.list_item_notifications, viewGroup, false); 
    TextView textView = (TextView) rowView.findViewById(R.id.text_notification); 
    textView.setText(theStringArray[position]); 
} 

这发生可怕的事情,因为“theStringArray”不是一个字符串数组在所有的,只是一个int指的是一个字符串数组。我想这是解决我的第一个问题的答案。

然而,从这一点上,我不知道如何添加一个意图,我可以给一个.putextra依赖于用户点击的项目。最后,如何给每个项目分配自己的图标?我应该在哪里存储这个图标列表,以及如何将其映射到正确的项目?

如果有人能够启发我,我将非常感激!

+0

检查此[线程](http://stackoverflow.com/questions/4691706/java-android-get-array-from-xml) – Aiapaec

回答

1

这是你如何加载字符串数组:

final String[] theStringArray = getResources().getStringArray(R.array.notifications_string_array); 
1
String[] sarray = getResources().getStringArray(R.array.notifications_string_array); 

现在可以将这个数组传递到适配器类的构造函数,并用它有

I want to put a custom icon next to the list item. 

你需要一个用textview和imageview自定义布局。在getView中隐藏自定义布局,并适当地更新textview和imageview。

I also want to be able to click every item 

您可以为textview和imageview设置侦听器。如果要单击行的侦听器,请使用setOnItemClickListener

listView.setOnItemClickListener(new OnItemClickListener() 
{ 

@Override 
public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) { 
TextView tv = (TextView)arg1.findViewById(R.id.text_notification); 
String text = tv.getText().toString(); 
Intent i = new Intent(ActivityName.this,SecondActivity.class); 
i.putExtra("key",text); 
startActivity(i);    

} 
}); 

对于可绘

int [] mydrawable ={R.drawable.icon1,R.drawable.icon2}; // pass this to the constructor of you adapter class 
+0

啊,感谢!字符串数组现在加载非常好。至于图标。我只是不知道应该在哪里存储图标列表,以及如何使.putextra依赖于所单击的项目。任何指针(或示例代码)都会非常受欢迎。 – kramer65

+0

@ kramer65你在哪里有图标? – Raghunandan

+0

在我的res/drawable /文件夹中,就像所有其他图标一样。但我想我需要在某处列出一个列表。没有更合乎逻辑的方式来做这件事,而不是在一个中心位置定义字符串,图标和putextras? – kramer65

相关问题