ちょうど1週間前にJavaとAndroid Development
を学習し始めました。私は知りたい基本的なことをいくつか持っています。アンドロイド:MainActivityクラスから継承できますか?
私のアプリケーションの機能は、10個のボタンがあり、それぞれが1回クリックされると無効になることです。合計5つのボタンがクリックされた場合、すべてのボタンを無効にする必要があります。 私はボタン配列を使用しませんでしたが、なぜこれが機能しないのかを知りたいと思います。 (必要なすべての輸入が行われている)
MainActivity
クラスはこのように書きます:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StartText();
}
Class1 c1object = new Class1();
TextView textobj;
Button Button1,Button2,Button3,Button4 /* similarly for the other 6 buttons*/ ;
public void StartText(){
textobj = (TextView)findViewById(R.id.textView);
textobj.setText("No Button has been clicked");
}
public void Click1(View view)
{
Button1 = (Button)findViewById(R.id.button1);
c1object.disablebutton(Button1,textobj,1);
}
public void Click2(View view)
{
Button2 = (Button)findViewById(R.id.button2);
c1object.disablebutton(Button2,textobj,2);
}
public void Click3(View view)
{
Button3 = (Button)findViewById(R.id.button3);
c1object.disablebutton(Button3,textobj,3);
}
public void Click4(View view)
{
Button4 = (Button)findViewById(R.id.button4);
c1object.disablebutton(Button4,textobj,4);
}
// Similarly for 6 more buttons
}
Class1
はこれです:
public class Class1 {
Class2 c2object = new Class2();
private int Clickcount=0;
public void disablebutton(Button b, TextView t, int i) {
b.setEnabled(false);
String str = Integer.toString(i);
t.setText("You clicked button: " + str);
Clickcount++;
if(Clickcount==5)
c2object.disableAll();
}
}
、最終的には、
Class2
はこのように書きます:
public class Class2 {
MainActivity mainobject = new MainActivity();
public void disableAll(){
mainobject.Button1.setEnabled(false);
mainobject.Button2.setEnabled(false);
mainobject.Button3.setEnabled(false);
mainobject.Button4.setEnabled(false);
//Similarly for the other 6 buttons
}
}
私は、この私のアプリの起動を実行しますが、白い画面が表示され、アプリが閉じた場合。
何度か試してみたら、MainActivity
クラスのオブジェクトを作成したときにいつも起こることに気付きました。 私もMainActivity
を継承しようとしましたが、結果は同じでした。
私もこれにClass2
を変更してみました:
public class Class2 {
public void disableAll(){
Button b1 = (Button)findViewById(R.id.button1);
b1.setEnabled(false);
//Similarly for the other 9 buttons
}
}
私はここにfindViewById
を使用できないことに気づきました。
これらは私が知りたいものがあります:私たちは
から継承や
MainActivity
のオブジェクトを作成することはできますか?MainActivity
以外の別のクラスのfindViewById
を使用できないのはなぜですか?Clickcount==5
の後にすべてのボタンを無効にするにはどうすればよいですか?あなたは私のコーディング方法を見てきました。私が従う必要があるプラクティスはどれですか?私のコーディング方法を改善するための他の提案はありますか?
ありがとうございました!
を、どこif文を持っていますif(Clickcount == 5){myButton.setEnabled(false); }あなたが必要とする多くのボタンのためにそれを行います。また、MainActivityクラスのインスタンスを作成することについてコードを構造化することはお勧めしません。オブジェクトのインスタンスを作成する必要がある場合は、そのために別のクラスを作成します。私はfindViewByIdの部分についてはよく分かりません。 – Michael
それは私がやったこととほとんど同じです。問題は、MainActivityのオブジェクトを作成せずにこのクラスからmyButtonにアクセスできないことです。しかし、そうすることは、私のアプリケーションをクラッシュさせることです。 –
MainActivityを静的にして、すべての無効化ボタンのコードをMainActivityの静的メソッドに入れることができます。ちょうどインスタンス化する必要はありません。クラッシュしたときにどんなエラーが出ますか? – Michael