【发布时间】:2018-07-16 11:46:53
【问题描述】:
我是 android 编程新手,当用户单击位于 tab1 中的按钮时,我找不到在 TabLayout 中的 tab1 和 tab2 之间切换的方法。
这可能是非常简单的事情,但我对我的第一个应用程序一无所知。
我一开始尝试了以下方法:
TabLayout.Tab tab = tabLayout.getTabAt(1);
tab.select();
它曾经可以工作,但我更改了代码,在某些时候,它就不再工作了。
我也试过tab.getCustomView().setSelected(true);,但我得到了 NullPointerException。所以我检查了一个 if 语句,如果 tab 为空,但它不是。
然后我尝试了
tabLayout.setScrollPosition(1,0f,true);
ViewPager viewPager = new ViewPager(mainView.getContext());
viewPager.setCurrentItem(1);
但上述解决方案均不适合我。
这是我的代码:
View view;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
try {
view = inflater.inflate(R.layout.fragment_main, container, false);
Button GoB = view.findViewById(R.id.GoB);
final EditText USETV = view.findViewById(R.id.USETV);
final EditText commandEV = view.findViewById(R.id.CommandTV);
final SqlHelper db = new SqlHelper(getContext(), "myDatabase", null, 1);
GoB.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
String a = "";
if (USETV.getText().toString().length() > 0) {
a += "USE " + USETV.getText().toString() + " ;";
}
a += commandEV.getText().toString();
String[][] c = db.SqlQuery(a);
LayoutInflater factory = getLayoutInflater();
View resultView = factory.inflate(R.layout.fragment_result, null);
TableLayout tableLayout = resultView.findViewById(R.id.ResultContainer);
tableLayout.removeAllViews();
View mainView = factory.inflate(R.layout.main_activity,null);
TabLayout tabLayout = mainView.findViewById(R.id.tabs);
if (c[0].length > 0 && c[1].length > 0) {
TabLayout.Tab tab = tabLayout.getTabAt(1);
//tab.select();
//tab.getCustomView().setSelected(true);
//tabLayout.setScrollPosition(1,0f,true);
//ViewPager viewPager = new ViewPager(mainView.getContext());
//viewPager.setCurrentItem(1);
//
// do some stuff
}
} catch (Exception e) {
showException(e);
}
}
});
} catch (Exception e) {
showException(e);
}
return view;
}
【问题讨论】:
标签: java android android-tablayout