привязка данных с динамическим представлением содержимого - PullRequest
0 голосов
/ 03 июня 2019

У меня есть навигационный ящик, который нужно использовать на двух экранах (первый, второй). Для этого я создал класс BaseActivity, который будет иметь реализацию панели навигации и один метод для динамического задания содержимого действия, как показано ниже.

public class BaseActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    protected View mainView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    protected void updateLayout(int layoutId){
        FrameLayout contentFrameLayout = (FrameLayout) findViewById(R.id.content_frame); //Remember this is the FrameLayout area within your activity_main.xml
        mainView = getLayoutInflater().inflate(layoutId, contentFrameLayout);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_first) {
            Intent intent = new Intent(this, FirstActivity.class);
            startActivity(intent);
        } else if (id == R.id.nav_second) {
            Intent intent = new Intent(this, SecondActivity.class);
            startActivity(intent);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

Метод updateLayout () будет динамически обновлять содержимое активности.

С этим я хочу установить привязку данных для первого экрана, что я не могу сделать. Вот мой код

public class FirstActivity extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        updateLayout(R.layout.content_first);

        EmployBean bean = new EmployBean("100", "Rajesh");
        ContentFirstBinding mBinding = DataBindingUtil.setContentView(this, R.layout.content_first);
        EmployViewModel employViewModel = ViewModelProviders.of(this).get(EmployViewModel.class);
        employViewModel.getEmployBean().setValue(bean);
        mBinding.setEmployViewModel(employViewModel);

    }
}

Показывает content_first в качестве основного контента без панели навигации.

Может кто-нибудь помочь мне, как решить эту проблему? Заранее спасибо.

Ответы [ 2 ]

2 голосов
/ 03 июня 2019

Избавьтесь от

updateLayout(R.layout.content_first);

и замените

ContentFirstBinding mBinding = DataBindingUtil.setContentView(this, R.layout.content_first);

на

ContentFirstBinding mBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.content_first, (FrameLayout) findViewById(R.id.content_frame), true)

, последняя строка позаботится о том, чтобы надуть макет для вас, идобавить его содержимое к (FrameLayout) findViewById(R.id.content_frame)

0 голосов
/ 03 июня 2019

Вы надуваете макет с помощью DataBindingUtil, но не устанавливаете его в FrameLayout,

не используете

updateLayout(R.layout.content_first);

Вместо этого сделайте это -

ContentFirstBinding mBinding = DataBindingUtil.setContentView(this,R.layout.content_first);
navigationView.addView(mBinding.getRoot())
...