Я пытаюсь показать изображение под кнопкой только после нажатия кнопки. Моя проблема в том, что фрагмент отображается сразу при запуске приложения, а не только после нажатия кнопки.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void say_hello(View view){
Fragment fragment = new ExampleFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment2, fragment).commit();
}
}
public class ExampleFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.news_articles, container, false);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:orientation="vertical"
android:layout_height="fill_parent"
tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center_vertical"
android:text="PRESS THIS"
android:id = "@+id/test_button"
android:background="@drawable/test_button"
android:onClick="say_hello"
/>
<fragment
android:id="@+id/fragment2"
android:name="com.example.tic_tac_toe.ExampleFragment"
android:layout_width="match_parent"
android:layout_height="643dp" />
</LinearLayout>
<ImageView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/cool_dog">
</ImageView>
Я предполагаю, что фрагмент появляется при запуске приложения из-за имени, которое я даю фрагменту в XML, но фрагмент должен имя, иначе я получаю только ошибку. Как заставить фрагмент ничего не отображать до того, как я нажму кнопку?