gpt4 book ai didi

java - 如何从 oncreate 方法 android 内部调用同一个类中的方法?

转载 作者:行者123 更新时间:2023-11-30 00:43:51 25 4
gpt4 key购买 nike

您好我是 android 和 java 的新手,每次单击一个按钮时,我都试图制作一个三按钮菜单,其他两个按钮更改其颜色或单击一个突出显示以显示它已被选中但我无法从中调用方法在 onCreate 中单击时执行特定任务。帮忙谢谢`

 public class MainActivity extends AppCompatActivity {

int PriceList;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button button1 = (Button)findViewById(R.id.Coffee);
Button button2 = (Button)findViewById(R.id.Mocha);
Button button3 = (Button)findViewById(R.id.Lattee);
TextView Counter = (TextView)findViewById(R.id.Counters);

mClick(button1,button2,button3)
mClick(button2,button1,button3)
mClick(button3,button2,button1)

Counter.setText(Item()); //Counter is a TextVew, This code doesn't work

}

**/*------------METHODS----------------*/**

public int TotalValue(int param5){

if(param5 == 2131427416){ //just Trying to compare with id value

Item();

Log.d("Item Value " , "onCreate: The value is " + Item()); // works upto here i.e Item()=1

} else{
// some other code here
}
}

public int Item(){

PriceList = 1;

return PriceList;
}

public void mClick(final Button param1,final Button param2,final Button param3){
param1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view){
param2.setBackgroundColor(Color.rgb(192,110,99));
param3.setBackgroundColor(Color.rgb(192,110,99));

int IdNum = param1.getId()

TotalValue(IdNum);

}
});
}
}
}

最佳答案

您不能在方法中定义方法:

public class Example {
void foo() {
void bar() { }
}

没用!去:

public class Example {
void foo() {
}
void bar() { }

相反。

除此之外,要理解的另一件基本事情是,为了让多个方法对相同的变量起作用,这些方法需要是您类的字段,例如:

public class Example {
private Button button1

void onCreate() {
...
button1 = (Button) findViewById(R.id.button1);
...
}

void foo() {
do something with button1
}

关于java - 如何从 oncreate 方法 android 内部调用同一个类中的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42111684/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com