从Android中的自定义布局获取变量?

时间:2016-01-28 18:03:11

标签: android

在android中,我有一个我自己构建的自定义布局:

public class ButtonMatch extends RelativeLayout
{
    private final TextView text_round, text_match, text_player1, text_player2;

    public ButtonMatch(final Context context) {
        super(context);
        LayoutInflater.from(context).inflate(R.layout.button_match, this, true);

        text_round = (TextView) findViewById(R.id.text_round);
        text_match = (TextView) findViewById(R.id.text_match);
        text_player1 = (TextView) findViewById(R.id.text_player1);
        text_player2 = (TextView) findViewById(R.id.text_player2);
    }

    public void setRound(String text) {
        text_round.setText(text);
    }

    public void setMatch(String text) {
        text_match.setText(text);
    }

    public void setPlayer1(String text) {
        text_player1.setText(text);
    }

    public void setPlayer2(String text) {
        text_player2.setText(text);
    }

    public String getPlayer1() {
        return text_player1.getText();
    }

    public String getPlayer2() {
        return text_player2.getText();
    }
}

然后我在代码中添加以下内容:

ButtonMatch button = new ButtonMatch(this);

button.setLayoutParams(layout);
button.setTag(match.get("id"));
button.setMatch(match.get("identifier").toString());
button.setPlayer1(players.get(match.get("player1_id").toString()));
button.setPlayer2(players.get(match.get("player2_id").toString()));
button.setOnClickListener(new View.OnClickListener()
{
    public void onClick(View view)
    {
        Intent intent = new Intent(view.getContext(), ChallongeMatch.class);
        intent.putExtra(MainActivity.EXTRA_API_KEY, API_KEY);
        intent.putExtra(MainActivity.EXTRA_SUBDOMAIN, SUBDOMAIN);
        intent.putExtra(MainActivity.EXTRA_EVENT_ID, EVENT_ID);
        intent.putExtra(MainActivity.EXTRA_MATCH_ID, view.getTag().toString());
        intent.putExtra(MainActivity.EXTRA_PLAYER1, view.getPlayer1());
        intent.putExtra(MainActivity.EXTRA_PLAYER2, view.getPlayer2());
    }
});

我缺少的是,在onClickListener的Intent中,我试图获取text_player1text_player2的内容,如下所示:

        intent.putExtra(MainActivity.EXTRA_PLAYER1, view.getPlayer1());
        intent.putExtra(MainActivity.EXTRA_PLAYER2, view.getPlayer2());

问题是这两个功能不起作用getPlayer1()getPlayer2,因为它们在视图中不存在...

如何使这两个功能起作用。我还不太了解Android / Java,所以请尽可能多地解释。

1 个答案:

答案 0 :(得分:1)

您忘了将select movieId, rating from tablename group by movieId having count(userId) > 1 and rating > 4; 投射到view

这是安全的,因为您在按钮对象上设置了单击侦听器。

将您的代码更改为

ButtonMatch

访问对象上的方法。