所以我在MainActivity上有这个代码:
public class MainActivity extends AppCompatActivity {
TextView missao, MissaoDia;
Button Change, Done;
int x = 0;
int[] array = new int[]{R.string.m1, R.string.m2, R.string.m3, R.string.m4, R.string.m5, R.string.m6, R.string.m7};
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
super.onCreate(savedInstanceState);
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
break;
case R.id.navigation_perfil:
Intent intent = new Intent(MainActivity.this, perfil.class);
startActivity(intent);
break;
case R.id.navigation_mais:
Intent intent1 = new Intent(MainActivity.this, mais.class);
startActivity(intent1);
break;
}
return true;
}
});
missaoTxt();
}
public void missaoTxt(){
setContentView(R.layout.activity_main);
missao = (TextView) findViewById(R.id.missao);
MissaoDia = (TextView) findViewById(R.id.MissaoDia);
Change = (Button) findViewById(R.id.Change);
Done = (Button) findViewById(R.id.Done);
missao.setText(array[x]);
}
public void TrocarMissao(View view) {
x = x+1;
missaoTxt();
}
我的BottomNavigationView有三个按钮," home"," perfil" (个人资料)和" mais" (更多),但他们都没有工作。我为每个人都有相应名字的活动。我尝试过关注youtube视频和其他教程,但我似乎无法使其发挥作用。 它没有显示任何错误消息,它们是可点击的,但不做任何事情。
PS:我是编程新手。
答案 0 :(得分:1)
您正在重置布局,这将删除所有先前初始化的视图和侦听器
public void missaoTxt(){
// setContentView(R.layout.activity_main);
// ^^^^^^^^^^^^^^^ remove this
missao = (TextView) findViewById(R.id.missao);
MissaoDia = (TextView) findViewById(R.id.MissaoDia);
Change = (Button) findViewById(R.id.Change);
Done = (Button) findViewById(R.id.Done);
missao.setText(array[x]);
}
并且不要通过从点击侦听器调用missaoTxt()
来反复初始化视图,因此请使用
public void missaoTxt(){
missao = (TextView) findViewById(R.id.missao);
MissaoDia = (TextView) findViewById(R.id.MissaoDia);
Change = (Button) findViewById(R.id.Change);
Done = (Button) findViewById(R.id.Done);
}
public void TrocarMissao(View view) {
x = x+1;
missao.setText(array[x]);
}