我試圖將ListView
放入片段中,但是我的應用崩潰了。 我跟着this guide學習如何將ListView
放入一個活動中,但我想將它放在一個片段中,所以我稍微更改了一下代碼。 這是我的片段:如何將ListView放入片段
公共類FaqFragment擴展片段{
public static Fragment newInstance() {
FaqFragment fragment = new FaqFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
private ListView listView1;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_faq, container, false);
Element element_data[] = new Element[]
{
new Element(R.drawable.goccia, "Goccia1"),
new Element(R.drawable.goccia, "Goccia2"),
new Element(R.drawable.goccia, "Goccia3"),
new Element(R.drawable.goccia, "Goccia4"),
new Element(R.drawable.goccia, "Goccia5")
};
ElementAdapter adapter = new ElementAdapter(getActivity(), android.R.layout.simple_list_item_1, element_data);
listView1 = (ListView)v.findViewById(R.id.listView1);
View header = (View)getLayoutInflater(savedInstanceState).inflate(R.layout.element, null);
listView1.addHeaderView(header);
listView1.setAdapter(adapter);
return v;
}
這是我ArrayAdapter
:
public class ElementAdapter extends ArrayAdapter<Element>{
FragmentActivity context;
int layoutResourceId;
Element data[] = null;
public ElementAdapter(FragmentActivity fragmentActivity, int layoutResourceId, Element[] data) {
super(fragmentActivity, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = fragmentActivity;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
WeatherHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((FragmentActivity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new WeatherHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
row.setTag(holder);
}
else
{
holder = (WeatherHolder)row.getTag();
}
Element element = data[position];
holder.txtTitle.setText(element.title);
holder.imgIcon.setImageResource(element.icon);
return row;
}
static class WeatherHolder
{
ImageView imgIcon;
TextView txtTitle;
}
}
這是我Element
:
public class Element {
public int icon;
public String title;
public Element(){
super();
}
public Element(int icon, String title) {
super();
this.icon = icon;
this.title = title;
}
}
該應用程序有3個標籤,當我刷到標籤頁的應用程序崩潰這裏是我已經寫的代碼(片段)。
在logcat中有這樣的錯誤:
03-13 11:25:39.455: E/AndroidRuntime(2840): at com.example.bluhackathon.ElementAdapter.getView(ElementAdapter.java:47)
我試圖刪除行47,48和ArrayAdapter
49和應用程序沒有崩潰(當然還有空元素的列表。
線47,48,49:
Element element = data[position];
holder.txtTitle.setText(element.title);
holder.imgIcon.setImageResource(element.icon);
嗨,檢查我的答案處理片段:http://stackoverflow.com/questions/17918198/how-to-keep-tabs-visible-on-every-activity/17918804#17918804我管理的片段listviews 。 –
這將有助於瞭解47號線發生的異常情況。 –