1

I've got a function:

public void vfShareQuote (String textToShare){
    Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_TEXT, textToShare);
    sendIntent.setType("text/plain");
    startActivity(sendIntent);
}

Also there is a lot programmatically created buttons, that's 2 of them:

Button agafon_1 = new Button(this);agafon_1.setText(R.string.agafon_1);llPreViewList.addView(agafon_1, lParams);
Button agafon_2 = new Button(this);agafon_2.setText(R.string.agafon_2);llPreViewList.addView(agafon_2, lParams);

Here is the OnClickListener:

OnClickListener oclShareQuote = new OnClickListener() {
    @Override
    public void onClick(View v) {
//Set the text based on the selected button and send it to function vfShareQuote
    switch (v.getId()) {
    case R.string.agafon_1:
        vfShareQuote(getResources().getText(R.string.name_agafon)+":\n"+getResources().getText(R.string.agafon_1));
        break;
    case R.string.agafon_2:
        vfShareQuote(getResources().getText(R.string.name_agafon)+":\n"+getResources().getText(R.string.agafon_2));
        break;
    }
    }
};

And of course:

agafon_1.setOnClickListener(oclShareQuote);
agafon_2.setOnClickListener(oclShareQuote);

But when you press the button - nothing happens. Why? Or is it programmatically create buttons? What to do? Translated by google.

4

3 回答 3

4

因为R.string.agafon_1andR.string.agafon_2不是 id。它们只是字符串资源的 id。将 id 设置为按钮并改为使用它们。使用喜欢

agafon_1.setId(id1);
agafon_2.setId(id2);

其中 id1 和 id2 是两个 int 。并使用它们

OnClickListener oclShareQuote = new OnClickListener() {
    @Override
    public void onClick(View v) {
//Set the text based on the selected button and send it to function vfShareQuote
    switch (v.getId()) {
    case id1:
        vfShareQuote(getResources().getText(R.string.name_agafon)+":\n"+getResources().getText(R.string.agafon_1));
        break;
    case id2:
        vfShareQuote(getResources().getText(R.string.name_agafon)+":\n"+getResources().getText(R.string.agafon_2));
        break;
    }
    }
};
于 2013-06-28T11:51:00.987 回答
0

问题出在开关块中..您没有为按钮设置 Id 并且您正在尝试访问它们onClick..

尝试

agafon_1.setId(1);
agafon_2.setId(2);

然后在 switch 块中使用这些 id

OnClickListener oclShareQuote = new OnClickListener() {
    @Override
    public void onClick(View v) {
//Set the text based on the selected button and send it to function vfShareQuote
    switch (v.getId()) {
    case 1://agafon_1 is clicked
        vfShareQuote(getResources().getText(R.string.name_agafon)+":\n"+getResources().getText(R.string.agafon_1));
        break;
    case 2://agafon_2 is clicked
        vfShareQuote(getResources().getText(R.string.name_agafon)+":\n"+getResources().getText(R.string.agafon_2));
        break;
    }
    }
};
于 2013-06-28T11:52:55.057 回答
0

以编程方式创建按钮时,您应该以这种方式为每个按钮提供一个 id:

agafon_1.setId("btn id");

还有一个问题,对于某些 android sdks switch case 不再起作用,您必须使用 if 语句来实现。

于 2013-06-28T11:54:51.067 回答