Android - 带有两个按钮的片段
问题描述:
我正在构建一个具有带有两个按钮(“新闻”或“社交”)的片段的Android应用程序。它被初始化为新闻,然后如果在运行时单击“社交”按钮,它应该刷新与社交相关内容的片段。有没有办法做到这一点?Android - 带有两个按钮的片段
答
一种方式做到这一点是把在片段和展示两个视图/正常隐藏:
<!-- News -->
<FrameLayout
android:id="@+id/news_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- News content -->
</FrameLayout>
<!-- Social -->
<FrameLayout
android:id="@+id/social_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Social content -->
</FrameLayout>
然后,在Java中,你使用这些容器:
// show news and hide social example
socialContainer.setVisibility(View.GONE)
newsContainer.setVisibility(View.VISIBLE)
+0
谢谢,效果很好:) –
答
是的,你可以通过在单击按钮监听器上设置UI元素的值并传递单击按钮的相应内容来完成。但是,如果您想要以不同的方式表示信息,则需要根据点击的按钮制作容器布局并设置可见性。
答
在您的新闻选项卡中,你可以通过下面的代码
newsBtn.setOncliclListener(this);
socialBtn.setOncliclListener(this);
,并在你的onclick方法达到同样的写下来的代码,根据BTN点击更新视图
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.newsbtn:
socailview.setVisibility(View.GONE);
newsview.setVisibilty(View.VISIBLE);
loadYourNewsViewData();
break;
case R.id.socialbtn:
newsview.setVisibilty(View.GONE);
socailview.setVisibility(View.VISIBLE);
loadYourSocialViewData();
break;
}
}
答
你可以在您的主要活动中使用此代码加载新闻片段作为第一个片段
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="name of your news fragment class"
android:id="@+id/newsFragment"/>
答
就个人而言,我想:
做一个容器
Fragment
(只是你的这两个按钮),其中包含一个FrameLayout
。创建一个基本抽象类
BaseNewsFragment
,它将成为您的NewsFragment
和SocialFragment
的父级。依赖哪个按钮被点击的,我会打电话的方法有特异性片段
变化按钮单击事件 – sasikumar
片段你实现什么至今的说法来取代
FrameLayout
的内容?你已经试过了吗?该问题应该更针对具体问题 – Fabio