我有一个Fragment,我从MainActivity类调用它:-)。
以下是片段代码:
public class PersonFragment extends Fragment {
private static final String ARG_NAME = "name";
private static final String ARG_FIRSTNAME = "firstname";
ListView lst;
String[] name = {"Dockar","Nilson"};
String[] firstname = {"Jack","Michel"};
public static PersonFragment newInstance(String[] name, String[] firstname) {
PersonFragment fragment = new PersonFragment();
Bundle args = new Bundle();
args.putStringArray(ARG_NAME, name);
args.putStringArray(ARG_FIRSTNAME, firstname);
fragment.setArguments(args);
return fragment;
}
Activity mainActivity;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.person_fragment, container, false);
lst = view.findViewById(R.id.listviewperson);
CustomeListviewAdapterTest customeListview = new CustomeListviewAdapterTest(this.mainActivity,name,firtname);
lst.setAdapter(customeListview);
lst.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
if(position == 0) {
Intent intent = new Intent(getContext(),Jack.class);
startActivity(intent);
}if(position == 1) {
Intent intent = new Intent(getContext(),Michel.class);
startActivity(intent);
}
}
});
if (getArguments() != null) {
name = getArguments().getStringArray(ARG_NAME);
firstname = getArguments().getStringArray(ARG_FIRSTNAME);
}
return view;
}
字符串
我不知道如果一切都好,我没有Android Studio IDE上的错误.
现在我想从MainActivity调用它。所以我把它放在菜单上:
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.drawer_person:
PersonFragment fragment = PersonFragment.newInstance(HAVE ERROR HERE);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment).addToBackStack(null).commit();
break;
型
在newInstance()上,我不知道如何从我的Array调用String Data:
String[] name
和
String[] firstname
有人可以帮助我如何做到这一点吗?
此致,
1条答案
按热度按时间swvgeqrz1#
在创建
PersonFragment
的示例时,您似乎希望将字符串数组name和firstname传递给PersonFragment
。为此,您需要修改newInstance方法以接受这些数组作为参数。以下是如何做到这一点:在
PersonFragment
类中,修改newInstance方法,如下所示:字符串
现在,在你的
MainActivity
中,你可以像这样用你的字符串数组作为参数来调用这个方法:型
这样,在创建PersonFragment的示例时,您将name和firstname数组传递给PersonFragment,并且这些值将在片段中可访问。您的代码应该可以正确地使用此修改。