我想在運行時添加項目到放置在選項卡上的ListView。 但是當我這樣做,我得到一個錯誤。有3個標籤,我不使用ListFragments,因爲我已經在所有選項卡將項目添加到ListView
我的代碼如下
SwipeTabFragment.java
public class SwipeTabFragment extends Fragment {
private String tab;
private int color;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
tab = bundle.getString("tab");
color = bundle.getInt("color");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.bookshelf, null);
TextView tv = (TextView) view.findViewById(R.id.textView);
tv.setText(tab);
view.setBackgroundResource(color);
return view;
}
}
TabPagerAdapter.java
public class TabPagerAdapter extends FragmentPagerAdapter {
public TabPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int index) {
Bundle bundle = new Bundle();
String tab = "";
int colorResId = 0;
SwipeTabFragment swipeTabFragment = new SwipeTabFragment();
switch (index) {
case 0:
tab = "BookShelf";
bundle.putString("tab",tab);
swipeTabFragment.setArguments(bundle);
return swipeTabFragment;
// break;
case 1:
tab = "Now Listening";
colorResId = R.color.color2;
BookFragment bookFragment = new BookFragment();
return bookFragment;
//break;
case 2:
tab = "Library";
colorResId = R.color.color3;
TabLibrary tabLibrary = new TabLibrary();
return tabLibrary;
break;
}
return null;
}
@Override
public int getCount() {
return 3;
}
}
不同的內容
TabLibrary.java
public class TabLibrary extends Fragment {
final String LOG_TAG = "myLogs";
ListView lvLibList;
ImageButton btAddItem;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.library, parent, false);
ListView lvLibList = (ListView)v.findViewById(R.id.lvLibList);
ImageButton btn = (ImageButton)v.findViewById(R.id.btAddItem);
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, list);
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText edit = (EditText)v.findViewById(R.id.eAddItem);
list.add(edit.getText().toString());
edit.setText("");
adapter.notifyDataSetChanged();
}
};
btn.setOnClickListener(listener);
lvLibList.setAdapter(adapter);
return v;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
什麼錯誤?發佈logcat以及 – 2014-10-07 16:36:54
只是一個猜測 - 你可以嘗試在'TabLibrary.java'中嘗試使用'adapter.add(edit.getText()。toString())'而不是'list.add(...)'嗎?此外,這不會導致錯誤 - 所以發佈錯誤將幫助我們爲您提供比野生猜測更好的解決方案。 – 2014-10-07 16:55:59
在第一篇文章中完成 – RyndinV 2014-10-07 16:56:25