我是 Android 的新手,我正在实现一个小项目,在这个项目中,我有来自一个 Drupal 网站的新闻。这个应用程序有 3 个选项卡,每个选项卡都有一个包含特定内容的文章列表。文章列表由按线性布局排列的 TextView 和 ImageView 创建。当我单击标题时,文章打开并显示详细信息。这些文章是通过 HTTP POST
和 ViewJSON
模块从 Drupal 站点加载的。使用 FragmentActivity
和 TabHost
创建选项卡。一切正常,直到这里都可以正常工作。
我的问题是我想制作一个刷新按钮,放在选项卡上,当我按下它时,文章列表必须刷新或重新加载并保持当前选项卡打开。 我试图替换选项卡 fragment 内容并重新打开它,但是当我点击一篇文章的标题打开它时,选项卡内容仍然在所有 fragment 下的堆栈中。我提到当我点击文章标题时,一个新的 fragment 正在打开。我发送了文章的 ID 作为参数,并在同一 fragment 中打开了文章的内容。
我尝试使用这段代码但没有成功。
Button btn_refresh = (Button) findViewById(R.id.btn_refresh);
btn_refresh.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String current_tab = mTabHost.getCurrentTabTag();
if(current_tab.contains("POPULARE")){
Fragment f;
f = new PopulareActivity();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.tot,f);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
if(current_tab.contains("RECOMANDATE")){
Fragment f;
f = new RecomandateActivity();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.tot,f);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
}
});
更确切地说,我进入应用程序,按 Tab2(显示来自 tab2 的文章列表),按刷新按钮,打开一篇文章,按移动设备的后退按钮并显示 tab2 的内容。现在,我在 tab1 上输入(并显示 tab1 中的文章列表),从 tab1 列表中打开一篇文章,显示我需要的内容,然后在移动设备上按后退按钮。此时显示的是 tab2 内容(文章列表从我按下刷新按钮的地方形成 tab2。)。
要打开我使用的文章的详细信息:
tv.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Fragment f;
f = new DetaliiActivity();
Bundle data = new Bundle();
data.putInt("id", nid);
f.setArguments(data);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.tot,f);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
});
在此先感谢您的帮助!
最佳答案
要刷新 fragment 的内容,您可以保留对该 fragment 的引用,并在该 fragment 中调用公共(public)(例如)refresh()
方法。示例:
public class ArticleTabFragmentActivity extends FragmentActivity{
private PopulareFragment populareFragment;
private RecomandateFragment recomandateFragment;
<code>
private void bindView(){
Button btn_refresh = (Button) findViewById(R.id.btn_refresh);
btn_refresh.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String current_tab = mTabHost.getCurrentTabTag();
if(current_tab.contains("POPULARE")){
populareFragment.refresh();
} else if(current_tab.contains("RECOMANDATE")){
recomandateFragment.refresh();
}
});
}
}
public class PopulareFragment extends Fragment{
public void refresh(){
<refresh the contents of the fragment>
}
}
<Same for other fragment>
现在,当您创建选项卡 fragment (如 PupulareFragment)时,请使用 pupulareFragment 实例变量来存储该 fragment 。所以在刷新按钮的onClick方法中可用。
这样你就不会在刷新时替换/创建任何新 fragment 。因此,在转到文章详细信息 Activity 后返回 tabActivity 可能也能正常工作。
关于android - 如何在单击按钮时刷新 fragment 选项卡内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13626956/