好吧,我想处理的某些“ TabItems”的“ ClickListeners”无法正常工作。
TabItem TabItem1;
View.OnClickListener Klick = new View.OnClickListener() {
public void onClick(View v) {
switch(v.getId()) {
case R.id.guiTabItem1:
Toast.makeText(MainActivity.this,"Lol wtf asdsadfdfs", Toast.LENGTH_LONG);
break;
case R.id.guiTabItem2:
// test
break;
}
}
};
应用程序已加载,但按选项卡上的按钮无效。我还尝试使用“ setOnClickListener”将click事件分配给选项卡。这会导致崩溃。
tabItem1.setOnClickListener(Klick);
并且以下尝试也无效:
tabItem1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,"Lol", Toast.LENGTH_LONG);
}
});
这是完整的代码片段。提前致谢!
public class MainActivity extends Activity {
ListView Liste;
MediaPlayer Player;
TabLayout guiTopNav;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabItem TabItem1 = findViewById(R.id.guiTabItem1);
View.OnClickListener Klick = new View.OnClickListener() {
public void onClick(View v) {
switch(v.getId()) {
case R.id.guiTabItem1:
Toast.makeText(MainActivity.this,"Lol wtf asdsadfdfs", Toast.LENGTH_LONG);
break;
case R.id.guiTabItem2:
// it was the second button
break;
}
}
};
tabAndreas.setOnClickListener(Klick);
}
最佳答案
因此,我制定了解决方案。显然,setOnClickListener()与TabItems或TabLayouts不兼容。而是,使用以下解决方案为选项卡创建单击功能。当然,必须在设计器中将三个TabItem归类为一个TabLayout。
// #################################################################### GUI
TabLayout guiTabs;
guiTabs = findViewById(R.id.guiTopNav);
guiTabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
switch(tab.getPosition()) {
case 0: Toast.makeText(MainActivity.this, "Tab 1", Toast.LENGTH_LONG).show();
break;
case 1: Toast.makeText(MainActivity.this, "Tab 2", Toast.LENGTH_LONG).show();
break;
case 2: Toast.makeText(MainActivity.this, "Tab 3", Toast.LENGTH_LONG).show();
break;
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});