我试图添加String
项目,我的ListView
使用Fragments
。
我有四个Buttons
。 每一次Button
被点击, ListView
应该添加一个String
项:“按钮1,2,3或4单击”
问题是,它使更换第一String
与点击的项目Button
String
。 它不创建新项目。
这里是我的代码:
ListViewFragment.java:
public class ListViewFragment1 extends Fragment {
protected ArrayAdapter<String> adapter1;
@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.list_view_fragment1, container, false);
}
public void changeText(String data){
//Build Adapter
adapter1 = new ArrayAdapter<String>(getActivity(), R.layout.items);
//Configure the list view
ListView list1 = (ListView) getActivity().findViewById(R.id.listview1);
list1.setAdapter(adapter1);
adapter1.add(data);
adapter1.notifyDataSetChanged();
}
}
ButtonLayoutFragment.java:
public class ButtonLayoutFragment extends Fragment implements View.OnClickListener {
Communicator comm;
@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.buttons_layout, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
comm = (Communicator) getActivity();
Button[] bttn_arr = new Button[] {b0, b1, b2, b3};
button_list.addAll(Arrays.asList(bttn_arr));
button_list.set(0,(Button) getActivity().findViewById(R.id.button0));
button_list.set(1,(Button) getActivity().findViewById(R.id.button1));
button_list.set(2,(Button) getActivity().findViewById(R.id.button2));
button_list.set(3,(Button) getActivity().findViewById(R.id.button3));
for(Button b:button_list){
b.setOnClickListener(this);
}
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.button0:
comm.respond("item0 added");
break;
case R.id.button1:
comm.respond("item1 added");
break;
case R.id.button2:
comm.respond("item2 added");
break;
case R.id.button3:
comm.respond("item3 added");
break;
}
}
}
MainActivity.java:
public class MainActivity extends Activity implements Communicator {
FragmentManager manager;
ListViewFragment1 frag2;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.game_activity);
ButtonLayoutFragment frag = new ButtonLayoutFragment();
frag2 = new ListViewFragment1();
ListViewFragment2 frag3 = new ListViewFragment2();
manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.FragmentLayout, frag, "Fragment");
transaction.add(R.id.fragment2, frag2, "Fragment2");
transaction.commit();
}
@Override
public void respond(String data) {
frag2.changeText(data);
}
}
Communicator.java:
public interface Communicator {
public void respond(String data);
}
这是所有相关的代码。 我想我正确连接片段。 我认为这个问题是ListViewFragment1
-我可能没有使用adapter
正确。 我尝试了许多不同的方法,但什么也没有工作。 是否有人可以帮助?
*提醒-我只是想在ListView
每一次创建一个新的项目Button
被点击。 目前,只替换第一个项目。