简体   繁体   English

单击ListView项时打开一个新片段

[英]Opening a new fragment when a ListView item is clicked

I'm pretty new to Android so I may be doing things completely wrong but I'm trying to get a fragment to open up when a list item is clicked and then to close it when it is dismissed with the back button. 我是Android的新手,所以我可能做的事情完全错了,但是我试图让一个片段在单击列表项时打开,然后在使用后退按钮将其关闭时将其关闭。

I now have something working but when the back button is clicked it redraws the whole initial view. 我现在有一些工作,但是当单击后退按钮时,它将重新绘制整个初始视图。 SO the listview scrolls back up to the top and reloads all the items from the db. 因此,列表视图将滚动回到顶部并重新加载数据库中的所有项目。

On the list item click in the main activity I am doing this 在列表项上,单击我正在执行的主要活动

public void onItemSelected(String id) {
    Intent detailIntent = new Intent(this, DetailActivity.class);
    detailIntent.putExtra(Fragment.CLICKED_ID, id);
    startActivity(detailIntent);
}

Then in the activity I am using this to show it. 然后在活动中,我用它来展示它。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_open_day);

    // Show the Up button in the action bar.
    getActionBar().setDisplayHomeAsUpEnabled(true);


    if (savedInstanceState == null) {
        // Create the detail fragment and add it to the activity
        // using a fragment transaction.

        OpenDayFragment fragment = new OpenDayFragment();
        getFragmentManager().beginTransaction()
                .add(R.id.open_day_detail_container, fragment)
                .commit();
    }
}

and this to close it. 然后关闭它。

public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == android.R.id.home) {
        NavUtils.navigateUpTo(this, new Intent(this, MainActivity.class));
        return true;
    }
    return super.onOptionsItemSelected(item);
}

AS i said it all works but the listview and all the tabs from MainActivity seem to be completley disposed of when the activity is run. 正如我所说的那样,所有方法都可以正常运行,但是在运行该活动时,MainActivity的listview和所有选项卡似乎已全部销毁。 Is there a way just to show a fragment over the top and dismiss it, leaving the previosu activity intact? 有没有一种方法可以显示一个片段在上方并消除它,而使previosu活动保持原样?

Thanks 谢谢

On close button you are recreating the home activity which will as a result launch every thing again. 在关闭按钮上,您正在重新创建家庭活动,结果将再次启动所有内容。 To void that you should finish the DetailActivity that will take you back to the Home Activity. 要使此无效,您应该完成DetailActivity ,它将带您回到Home Activity。

It reloads it again because you are creating the MainActivity again. 它将再次重新加载它,因为您正在重新创建MainActivity。 To avoid that try finish(); 为了避免这种情况,请尝试finish(); in if (id == android.R.id.home) of your DetailActivity so it closes it, keeping the preview state of the MainActivity. 在DetailActivity的if (id == android.R.id.home) ,以便将其关闭,并保持MainActivity的预览状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM