我有一个Actiity,我有一个简单的Edittext和一个按钮作为shwown:
不,我有一个包含许多片段的MainActivity,如下所示:
这是我的代码,用于将edittext文本传递给主要活动:
addlist = (ImageButton) findViewById(R.id.btnaddlist);
findViewById(R.id.btnaddlist).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View arg0) {
EditText edit = (EditText) findViewById(R.id.txtlist);
Intent i = new Intent(CreateList.this,
MainActivity.class);
Bundle bundle = new Bundle();
String ItemName = edit.getText().toString();
// Add your data from getFactualResults method to bundle
bundle.putString("ListItemName", ItemName);
// Add the bundle to the intent
i.putExtras(bundle);
startActivity(i);
}
});
}
这是我的家庭片段:
ListView lv;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
lv = (ListView) getView().findViewById(R.id.itemslistView);
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
Bundle itemintent = getActivity().getIntent().getExtras();
String ItemName = itemintent.getString("ListItemName");
if (itemintent.getString("ListItemName").equals("ItemName")) {
/** Items entered by the user is stored in this ArrayList variable */
ArrayList<String> list = new ArrayList<String>();
list.add(ItemName);
/** Declaring an ArrayAdapter to set items to ListView */
ArrayAdapter<String> Listadapter;
Listadapter = new ArrayAdapter<String>(getActivity().getApplicationContext(),android.R.layout.simple_list_item_1, list);
Listadapter.notifyDataSetChanged();
}
return rootView;
}
我没有在logcat中收到任何错误。但是它无法在MainActivity上向listView添加任何文本。
答案 0 :(得分:0)
您制作了适配器,但没有调用ListView#setAdapter()
答案 1 :(得分:0)
更改您的Home片段:
ListView lv;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
lv = (ListView) getView().findViewById(R.id.itemslistView);
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
Bundle itemintent = getActivity().getIntent().getExtras();
String ItemName = itemintent.getString("ListItemName");
if (ItemName.equals("ItemName")) {
/** Items entered by the user is stored in this ArrayList variable */
ArrayList<String> list = new ArrayList<String>();
list.add(ItemName);
/** Declaring an ArrayAdapter to set items to ListView */
ArrayAdapter<String> Listadapter;
Listadapter = new ArrayAdapter<String>(getActivity().getApplicationContext(),android.R.layout.simple_list_item_1, list);
lv.setAdapter(Listadapter);
Listadapter.notifyDataSetChanged();// i don't think this line is necessary
}
return rootView;
}
答案 2 :(得分:0)
更好的方法如下:
希望这个答案可以帮到你。