我正在尝试在Android Studio中开发一个在Eclipse中运行良好的程序。但是按钮,听众和方法的新颖复杂性阻碍了我:我有类似按钮的集合,具有类似的动作。它们仅因索引值而不同。我试图创建一个对象类,名为bouton,扩展按钮并具有带参数j的实例方法。但它不起作用。到目前为止,重复每个按钮的代码是有效的,如下面的两个按钮所示。代码部分准备好进行for循环,但我的尝试让我无处可去。
package com....;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
// public static Button boutons[];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actionBouton1();
actionBouton2();
}
private void actionBouton1() {
String buttonID = "bouton" + 1;
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
final Button btnGenerique = (Button) findViewById(resID);
final TextView monMessage = (TextView) findViewById(R.id.affichage);
View.OnClickListener monEcouteur = new View.OnClickListener(){
@Override
public void onClick(View v){
monMessage.setText("you clicked button "+1);
}
};
btnGenerique.setOnClickListener(monEcouteur);
}
private void actionBouton2() {
String buttonID = "bouton" + 2;
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
final Button btnGenerique = (Button) findViewById(resID);
final TextView monMessage = (TextView) findViewById(R.id.affichage);
View.OnClickListener monEcouteur = new View.OnClickListener(){
@Override
public void onClick(View v){
monMessage.setText("you clicked button "+2);
}
};
btnGenerique.setOnClickListener(monEcouteur);
}
}// fin class MainActivity
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="btn 1"
android:id="@+id/bouton1"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="100dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="btn 2"
android:id="@+id/bouton2"
android:layout_alignTop="@+id/bouton1"
android:layout_toRightOf="@+id/bouton1"
android:layout_toEndOf="@+id/bouton1"
android:singleLine="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/affichage"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="200dp" />
</RelativeLayout>