在不更改片段信息的情况下更改活动

daupos2t  于 2021-06-29  发布在  Java
关注(0)|答案(0)|浏览(156)

我有两个活动和一个片段,在片段点击按钮时,我在第一个活动,并设置文本“你好”,然后我改变活动,并希望看到没有重新创建片段的你好。。。
... 片段代码。。。

public class FirstFragment extends Fragment {

TextView txtResult;
Button btnChange;

public FirstFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_first, container, false);
    txtResult = view.findViewById(R.id.fr1txtResult);
    btnChange = view.findViewById(R.id.fr1btnChange);
    btnChange.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            txtResult.setText("Hello");
        }
    });

    return view;
}

}
... 片段布局。。。

<LinearLayout 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:orientation="vertical"
android:padding="10dp"
android:background="@android:color/darker_gray"
tools:context=".FirstFragment">

<TextView
    android:id="@+id/fr1txtResult"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:text="Result is..."
    android:textAlignment="center"
    android:textColor="@color/white"
    android:textSize="30sp" />

<Button
    android:id="@+id/fr1btnChange"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="10dp"
    android:text="change" />

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题