【发布时间】:2019-10-29 15:53:53
【问题描述】:
我有几个列表视图项目,当我单击特定列表视图以转到具有被单击列表视图值的 Fragment_2 时,我需要。我在 Fragment_1 上尝试下面的代码,我得到了正确的值,它显示在 Tosat 通知中,但在 Fragment_2 中,捆绑始终为空。
在 Fragment_1 的 onCreate 方法中
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String value = ((TextView) view.findViewById(R.id.username)).getText().toString();
MainFragment fragment = new MainFragment ();
Bundle bundle = new Bundle();
bundle.putString("view", value);
Toast.makeText(getApplicationContext(), value, Toast.LENGTH_SHORT).show();
fragment.setArguments(bundle);
在 Fragment_2 的 onCreate 方法中
Bundle bundle = this.getArguments();
if (bundle != null) {
String myString = bundle.getString("view");
Toast.makeText(getContext(), myString, Toast.LENGTH_SHORT).show();
UDPATE:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String value = ((TextView) view.findViewById(R.id.username)).getText().toString();
MainFragment fragment = new MainFragment ();
Bundle bundle = new Bundle();
bundle.putString("view", value);
Toast.makeText(getApplicationContext(), value, Toast.LENGTH_SHORT).show();
fragment.setArguments(bundle);
if (position == 0) {
Intent myIntent = new Intent(view.getContext(), MainActivity.class);
startActivityForResult(myIntent, 0);
}
if (position == 1) {
Intent myIntent = new Intent(view.getContext(), MainActivity.class);
startActivityForResult(myIntent, 0);
}
if (position == 2) {
Intent myIntent = new Intent(view.getContext(), MainActivity.class);
startActivityForResult(myIntent, 0);
}
if (position == 3) {
Intent myIntent = new Intent(view.getContext(), MainActivity.class);
startActivityForResult(myIntent, 0);
}
// ETC .......
}
});
【问题讨论】:
-
添加setOnItemClickListener的完整代码。这样我就可以检查您是否使用正确的方法来替换片段。
-
我更新了代码
-
我看过你的代码。你没有使用片段。您在点击时打开新活动。所以你不会在其他活动中获得该片段的价值。
-
我打开该活动的另一个片段
-
然后你必须在新活动中传递数据,然后将其发送到目标片段。
标签: java android listview android-fragments bundle