基本上,我想根据哪个Fragment可见,从两个不同的表(或列)中获取Sqlite的数据。我已经找到了一个解决方案(棘手的解决方案),我想知道是否有其他最好的方法来达到相同的结果。我已经在一个片段上创建了很多教程。低于我所做的:
首先,在我的MainActivity中,我有:
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
toolbar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(),"Hai cliccato la barra",Toast.LENGTH_SHORT).show();
fragment = new HomeFragment();
if (fragment!=null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.screen_area,fragment);
ft.commit();
}
}
});
从navigationView我可以选择我想要看到的片段:
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
}
if (fragment!=null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.screen_area,fragment);
ft.commit();
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
int id= item.getItemId();
switch(id){
case R.id.carburante:
fragment = new CarburanteFragment();
break;
case R.id.giorni:
fragment = new GiorniFragment();
break;
...之后在我的CarburanteFragment上我将片段传递给DbAdapter ...例如在“Save”中:
private void save(String name)
{
DBAdapter db=new DBAdapter(getActivity(),((MainActivity) getActivity()).fragment= this);
db.openDB();
boolean saved=db.add(name);
if(saved)
{
nameEditText.setText("");
this.getSpacecrafts();
}else {
Toast.makeText(getContext(),"Unable To Save",Toast.LENGTH_SHORT).show();
}
}
...最后在DBAdapter类中,我可以获取我想要填充ListView的片段....例如更改Constants变量等等....在下面的代码中,我测试了它是否有效:< / p>
public DBAdapter(Context c,Fragment fr) {
this.c = c;
helper = new DBHelper(c);
Fragment currentFragment =fr;
if(currentFragment.getTag()=="carburante")
Toast.makeText(c, currentFragment.toString(), Toast.LENGTH_LONG).show();
}
答案 0 :(得分:0)
你可以做的是你可以在替换片段时传递一个标志,以后可以用它来识别你要加载的数据。
对于fragment1
Fragment1 frag = new Fragment1();
Bundle bundle = new Bundle ();
bundle.put("MY_FLAG", 1);
frag.setArgument(bundle);
对于fragment2
Fragment2 frag = new Fragment2();
Bundle bundle = new Bundle ();
bundle.put("MY_FLAG", 2);
frag.setArgument(bundle);
然后,您可以使用标志中的数据来标识要加载的数据类型。