Reputation: 85
Well, my "ClickListeners" for certain "TabItems" which I would like to handle do not work unfortunately.
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;
}
}
};
The app loads but pushing on a tab has no effect. I also tried assigning the click event to the tabs with "setOnClickListener". This results in a crash.
tabItem1.setOnClickListener(Klick);
And the following attempt also did not work:
tabItem1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,"Lol", Toast.LENGTH_LONG);
}
});
Here's the whole code snippet. Thanks in advance!
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);
}
Upvotes: 1
Views: 977
Reputation: 85
So, I worked out a solution. Apparently, the setOnClickListener() is not compatible with TabItems or TabLayouts. Instead, use the following solution to create a click function for tabs. Of course, three TabItems have to be categorized under one TabLayout in your designer.
// #################################################################### 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) {
}
});
Upvotes: 3
Reputation: 46
After declaring the TabItem object you have to assign the TabItem view to it by using the findViewById method.This method will find the correct view by it's id and will return the view.
TabItem tabItem1 = findViewById(R.id.tabitemview);
Upvotes: 0
Reputation: 66
And you already get the tabItem1 from the viewbyid?
/*Example you need to do it with the tabitem*/
button = (Button) findViewById(R.id.but);
Upvotes: 0