Есть вот такая задача.
Есть два фаргмента.
fragment1
= 3 кнопки
fragment2
= текстовое поле.
Хочу что бы они взаимодействовали друг с другом через Activity.
Сделал следующее. В первом фрагменте на каждую кнопку повесил слушатели по клику, где и сохраняется индекс кнопки. вот код.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment1, container, false);
button = (Button) rootView.findViewById(R.id.button);
button2 = (Button) rootView.findViewById(R.id.button2);
button3 = (Button) rootView.findViewById(R.id.button3);
button.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
return rootView;
}
@Override
public void onClick(View v) {
int buttonIndex = getIndex(v.getId());
}
public int getIndex(int id){
int index = -1;
if (id==R.id.button) {
index = 1 ;
}
if (id==R.id.button2) {
index = 2 ;
}
if (id==R.id.button3) {
index = 3 ;
}
return index;
}
во втором фрагменте ничего сложного, просто вставляют текст из массива. Есть один метод.
public void setDiscription(int index){
String text = mCatDescriptionArray[index];
textView.setText(text);
}
А как теперь активити узнает что я нажал по кнопке в первом фрагменте, и в этот момент мне надо поменять текст во втором фрагменте?