Я пытался решить эту проблему в течение нескольких дней и все еще не могу понять это. Я проверил многие похожие темы об этом, но не понял, что мне нужно.вызов метода из фрагмента внутри mainactivity
Как вы можете видеть, я динамически добавлять фрагменты:
public void displayFragment1() {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, new Fragment_1(), "frag1");
fragmentTransaction.commit();
}
public void displayFragment2() {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, new Fragment_2(), "frag2");
fragmentTransaction.commit();
}
Вот та часть, что я не могу понять. Я ищу фрагменты по тегу, и кажется, что он не работает, так как я всегда получаю исключение nullopinter или classexception. Тост просто показывает значение введенного мной текста, поэтому он отправляет данные из фрагмента в действие. так что часть в порядке. Любые идеи парней ???
@Override
public void inputValue(String text) {
if (text != null) {
Toast.makeText(MainActivity.this, text, Toast.LENGTH_SHORT).show();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, new Fragment_2(), "frag2");
fragmentTransaction.commit();
FragmentManager fm = getSupportFragmentManager();
Fragment_2 fragment = (Fragment_2) fm.findFragmentByTag("frag2");
fragment.setChangeTo(text);
} else {
Toast.makeText(MainActivity.this, "didnt recieve the value", Toast.LENGTH_SHORT).show();
}
}
активность Основной XML
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.example.neven.question_for_stackoverflow.MainActivity"
android:background="@drawable/my_background">
<FrameLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/fragment_container">
</FrameLayout>
MainActivity:
public class MainActivity extends AppCompatActivity implements Fragment_1.sendData {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
displayFragment1();
}
фрагмент 1 XML:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.neven.question_for_stackoverflow.Fragment_1"
android:background="@drawable/my_background">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_blank_fragment"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="fragment 1"
android:id="@+id/textView" android:layout_gravity="center"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/etInputID" android:layout_gravity="center" android:layout_marginTop="50dp"
android:hint="enter text here" android:textColorHint="#e3ca0a"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send"
android:id="@+id/bSendID" android:layout_gravity="center_horizontal|bottom"
android:layout_marginBottom="130dp"/>
фрагмент 2 XML
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.neven.question_for_stackoverflow.Fragment_2"
android:background="@drawable/my_background">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_blank_fragment"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="fragment 2 - change me"
android:id="@+id/tvChangeMeID" android:layout_gravity="center"/>
Пожалуйста, покажите свой макет XML, в котором вы определяете фрагмент или его «Framelayout», - нам нужно подтвердить атрибут 'id' вашего framelayout - это' id', который вы бы использовали с методом 'findFragmentById (id)'. – ishmaelMakitla
Я использую значение по умолчанию (android.R.id.content) – Nenco
Привет, пожалуйста, обновите свой вопрос, включив XML-файл макета, а также покажите нам метод 'onCreate' вашей' Activity' - нам нужно изучить эти и предложить решения вашей проблемы. – ishmaelMakitla