NavigationDrawerActivityでHomeにHelloWorldを表示する方法。NavigationDrawerActivityを選択して、アプリを作成します。
通常下記のような動作のものが完成します。
Homeを選択
This is home fragmentが表示されます
HomeFragment.java
import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProvider; import com.example.navidrawact.R; import com.example.navidrawact.databinding.FragmentHomeBinding; public class HomeFragment extends Fragment { private HomeViewModel homeViewModel; private FragmentHomeBinding binding; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { homeViewModel = new ViewModelProvider(this).get(HomeViewModel.class); binding = FragmentHomeBinding.inflate(inflater, container, false); View root = binding.getRoot(); final TextView textView = binding.textHome; homeViewModel.getText().observe(getViewLifecycleOwner(), new Observer() { @Override public void onChanged(@Nullable String s) { textView.setText("Hello World"); // ここを変更 } }); return root; } @Override public void onDestroyView() { super.onDestroyView(); binding = null; } }
HomeでHello Worldが表示されます。