我正在使用http://www.androidhive.info/2013/10/android-tab-layout-with-swipeable-views-1/制作标签栏。
我首先还有3个标签,第二个标签视图包含列表视图,第三个标签是设置。
设置包含重新加载按钮。当我点击重新加载按钮时,我想转到第一个标签。
我该怎么做?
答案 0 :(得分:6)
进行以下更改:
将viewPager引用传递给适配器,并将适配器传递给片段:
public class TabsPagerAdapter extends FragmentPagerAdapter {
ViewPager viewPager;
public TabsPagerAdapter(FragmentManager fm,ViewPager viewPager) {
super(fm);
this.viewPager=viewPager;
}
@Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Top Rated fragment activity
return new TopRatedFragment(viewPager);
case 1:
// Games fragment activity
return new GamesFragment(viewPager);
case 2:
// Movies fragment activity
return new MoviesFragment(viewPager);
}
return null;
}
@Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
}
在视图分页器对象上单击按钮调用集选择时的片段:
public class MoviesFragment extends Fragment {
private ViewPager viewPager;
public MoviesFragment (ViewPager viewPager;){
this.viewPager=viewPager;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_movies, container, false);
rootView.findViewById(<your button>).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
viewPager.setCurrentItem(0);
}
});
return rootView;
}
}
答案 1 :(得分:1)
我知道它已经很晚了......也许它可以帮助别人......不支持在片段中创建构造函数。所以不要将viewpager作为构造函数传递。 我们可以点击按钮点击片段:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by medha singh on 6/17/2016.
*/
public class Fragment4 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
final View view1 = inflater.inflate(R.layout.new_lead2, container, false);
TextView tv=(TextView)view1.findViewById(R.id.hardware);
final ViewPager pager= (ViewPager)getActivity().findViewById(R.id.pager2);
tv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pager.setCurrentItem(1);
}
});
return view1;
}
}
所以getactivity()就是解决方案:我从这里得到它:How to go other Tabs by clicking on a Button from the current Tab in Android?
答案 2 :(得分:0)
这样做:
btn.setOnClickListener(new OnClickListener()
{
onClick(View v)
{
//Reload the data
tabHost.setCurrentTab(/*destination-tab-id*/);
}
}
)