我正在尝试将字符串发送到我的列表视图。遗憾的是,数据未被发送并且没有显示任何错误。主活动具有列表视图,用户单击按钮(将它们带到第二个活动),在那里他们可以输入产品名称,并且应该自动将它们带回主活动。
这确实有效,但我必须搞砸了。我错过了什么吗?
MainActivity.java
public class MainActivity extends Activity {
private ListView listView;
private String[] details;
public static ArrayList<String> names = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
// replace \ with left angle bracket in the line below
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, names);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
}
);
}
}
第二项活动
public class Main2Activity extends Activity {
private EditText textName;
private EditText textModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
textName=(EditText)findViewById(R.id.inputName);
textModel=(EditText)findViewById(R.id.inpuModelNumber);
}
public void addNames(View v){
MainActivity.names.add(textName.getText().toString());
finish();
}
}
答案 0 :(得分:1)
据我所知,你想把字符串的数组列表传递给另一个活动
在您的活动中创建arraylist
public class Main2Activity extends Activity {
private EditText textName;
private EditText textModel;
ArrayList<String> names = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
textName=(EditText)findViewById(R.id.inputName);
textModel=(EditText)findViewById(R.id.inpuModelNumber);
}
public void addNames(View v){
names.add(textName.getText().toString());
Intent intent = new Intent(Main2Activity .this, MainActivity .class);
intent.putStringArrayListExtra("keyNames", names);
startActivity(intent);
finish();
}
}
然后解析传递的字符串数组
在oncreate中
Intent i = getIntent();
ArrayList<String> list = i.getStringArrayListExtra("keyNames");
我希望这可以帮到你
答案 1 :(得分:1)
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent newPage = new Intent(getActivity().getApplicationContext(),
Main2Activity.class);
newPage.putExtra("TITLE", title);
newPage.putExtra("DATE", date);
newPage.putExtra("CONTENT", content);
startActivity(newPage);
}
}
);
}
然后在Main2Activity的onCreate()方法中:
Bundle extras = getIntent().getExtras();
if(extras !=null) {
String title = extras.getString("TITLE");
String date = extras.getString("DATE");
String content = extras.getString("CONTENT");
}