如何在on-click()类中的按钮上设置文本? 我需要获取sq l select语句的按钮文本
tableLayout.addView(tableRow);
int a = 0;
for (Integer j = 0; j < count; j++)
{
Button b = new Button(getApplicationContext());
b.setText(c.getString(c.getColumnIndex("jour")));
b.setId(a++);
tableRow.addView(b);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Integer fff = v.getId();
Toast.makeText(getApplicationContext(), fff.toString(), Toast.LENGTH_SHORT).show();
Log.d("TAG", "The index is");
}
});
c.moveToNext() ;
enter code here
答案 0 :(得分:2)
您可以键入caste the view to按钮并将其用于getText()。
tableLayout.addView(tableRow);
int a = 0;
for (Integer j = 0; j < count; j++)
{
Button b = new Button(getApplicationContext());
b.setText(c.getString(c.getColumnIndex("jour")));
b.setId(a++);
tableRow.addView(b);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Integer fff = v.getId();
Toast.makeText(getApplicationContext(), fff.toString(),
Toast.LENGTH_SHORT).show();
Button b = (Button)v;
String buttonText = b.getText().toString();
Log.d("TAG", "The text is " + buttonText);
}
});
c.moveToNext() ;
答案 1 :(得分:1)
您正在将Button添加到表格行tableRow.addView(b);
。我一开始看代码看不到它。错过了。
所以让它成为最终
final Button b = new Button(getApplicationContext());
// Use ActivtiyContext
final Button b = new Button(ActivityName.this);
// posted a link at the end read it.
匿名类无法访问其封闭范围中未声明为final或者有效最终的局部变量。
http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html#accessing
在onClick内部
public void onClick(View v) {
String value = b.getText().toString()
}
同时检查
答案 2 :(得分:1)
按照我的方式创建String Array
和:
String Title = new String[count];
现在实施如下:
for (int j = 0; j < count; j++)
{
Button b = new Button(getApplicationContext());
b.setText(c.getString(c.getColumnIndex("jour")));
b.setId(j);
Title[a] = c.getString(c.getColumnIndex("jour");
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v1) {
Toast.makeText(getApplicationContext(), "Button click on(): "+Title[v1.getId()].toString(), Toast.LENGTH_SHORT).show();
Log.d("TAG", "The index is: "+v1.getId());
}
});
tableRow.addView(b);
c.moveToNext() ;
}
答案 3 :(得分:0)
首先为按钮提供onclick事件(按钮点击)。
答案 4 :(得分:0)
试试这段代码:
public void onClick(View v) {
String value = (Button)v.getText().toString()
}