0
剛剛接觸Android,所以只是練習一些小東西,試圖做的是在mainactivity佈局中的按鈕(B1),當我點擊它時,它會更改爲另一個佈局(main)其中有另一個按鈕(B2),它改回到主要活動佈局上點擊,B1正在工作,但B2沒有工作任何想法?Button not working in layout
package com.example.android;
import java.util.Random;
import java.awt.*;
import com.example.android.R;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
Button btn;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.clickme);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setContentView(R.layout.main);
/*Random rand = new Random();
btn.setBackgroundColor(Color.argb(255, rand.nextInt(255),
rand.nextInt(255), rand.nextInt(255)));*/
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
這是(主)佈局
package com.example.android;
import com.example.android.R;
import java.util.Random;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Main extends Activity {
Button btn;
TextView text;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.ChangeColor);
text = (TextView) findViewById(R.id.textView);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setContentView(R.layout.activity_main);
/*Random rand = new Random();
btn.setBackgroundColor(Color.argb(255, rand.nextInt(255),
rand.nextInt(255), rand.nextInt(255)));
text.setTextColor(Color.argb(255, rand.nextInt(255),
rand.nextInt(255), rand.nextInt(255)));*/
}
});
}
}
你'沒有從MainActivity導航到Main,你在那裏按鈕B2 –
的點擊事件在MainActivity中使用'Intent intent = new Intent(Ma inActivity.this,Main.Class); startActivity(intent); ';在Main中按鈕點擊使用'finish();' – Raghunandan
我試過了意圖,但是當我點擊時,程序崩潰了「不幸Android已經停止」 –