我有3个从同一个类文件生成的片段。这三个片段存在于ViewPager和FragmentStatePagerAdapter中。
他们在滑动标签中。它们只创建一次,从不被删除或删除或内存不足。
该应用程序到目前为止工作正常,但我需要弄清楚如何使片段知道自己的索引(1,2或3)。
是否有类似的代码:
int myIndex = summonTheAllKnowingThing.getWhatFragmentThisIsPlease();
我可以在以下代码中添加某个地方吗?
public class BlankFragment extends Fragment implements View.OnClickListener {
private boolean isDone = false;
EditText persons_name;
Spinner disc1_spinner;
Spinner disc2_spinner;
Spinner disc3_spinner;
Spinner fee1_spinner;
Spinner fee2_spinner;
EditText custom_disc;
EditText custom_fee;
Button doneButton;
public BlankFragment() {
// Required empty public constructor
}
public static BlankFragment newInstance() {
BlankFragment fragment = new BlankFragment();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_blank, container, false);
doneButton = (Button) v.findViewById(R.id.doneButton);
doneButton.setOnClickListener(this);
return v;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// getView().findViewById(R.id.
persons_name = (EditText) getView().findViewById(R.id.NAME);
disc1_spinner = (Spinner) getView().findViewById(R.id.DISC1);
disc2_spinner = (Spinner) getView().findViewById(R.id.DISC2);
disc3_spinner = (Spinner) getView().findViewById(R.id.DISC3);
custom_disc = (EditText) getView().findViewById(R.id.customDISC);
custom_fee = (EditText) getView().findViewById(R.id.customFEE);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.doneButton:
if MainActivity.is1Done
doneButton.setBackgroundColor(Color.RED);
MainActivity.name1 = persons_name.getText().toString();
break;
}
}
}
答案 0 :(得分:1)
最好的方法是在pager适配器中创建片段时传递索引,如
@Override
public Fragment getItem(int position) {
return BlankFragment.newInstance(position);
}
和 BlankFragment 将是
public class BlankFragment extends Fragment implements View.OnClickListener {
private int myIndex; //<-- access it for getting its index
//.. some other variables
public BlankFragment() {
// Required empty public constructor
}
public static BlankFragment newInstance(int indexInPager) {
BlankFragment fragment = new BlankFragment();
Bundle bundle = new Bundle();
bundle.putInt("index",indexInPager);
fragment.setArguments(bundle);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
myIndex = getArguments().getInt("index");
View v = inflater.inflate(R.layout.fragment_blank, container, false);
doneButton = (Button) v.findViewById(R.id.doneButton);
doneButton.setOnClickListener(this);
return v;
}
//.. some other code
}