setText使用资源作为占位符

时间:2016-09-19 01:56:32

标签: android

按照Android Boot Camp中的说明制作购买音乐会门票的应用程序。(非常基本)我的代码与本书非常相似。 在代码的最后,用户输入他们想要的票数,并且应该输出他们选择的票的票价。最后一行是我遇到问题的地方。我不明白为什么它不起作用,我没有找到任何解释为什么这是错误的以及如何解决它。

我查看了链接的答案,看它是否有帮助,但事实并非如此。

以下代码来自MainActivity.java

    public class MainActivity extends AppCompatActivity {
double costPerTicket = 79.99;
int numberOfTickets;
double totalCost;
String groupChoice;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final EditText tickets = (EditText)findViewById(R.id.txtTickets);
    final Spinner group = (Spinner)findViewById(R.id.txtGroup);
    Button cost = (Button)findViewById(R.id.btnCost);
    cost.setOnClickListener(new View.OnClickListener() {
        final TextView result = ((TextView)findViewById(R.id.txtResult));

        @TargetApi(Build.VERSION_CODES.N)
        @Override
        public void onClick(View v) {
            numberOfTickets = Integer.parseInt(tickets.getText( ).toString( ));
            totalCost = costPerTicket * numberOfTickets;
            DecimalFormat currency = new DecimalFormat("$###,###.##");
            groupChoice = group.getSelectedItem( ).toString( );
            result.setText("Cost for " + groupChoice + "is " + currency.format(totalCost));

        }
    }
    );

}

}

1 个答案:

答案 0 :(得分:0)

以下是修复“不连接文本”警告的答案。 (请注意,我没有包含你的string.xml字符串,因为我不知道它们的名字。)

public class MainActivity extends AppCompatActivity {
    double costPerTicket = 79.99;
    int numberOfTickets;
    double totalCost;
    String groupChoice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final EditText tickets = (EditText)findViewById(R.id.txtTickets);
        final Spinner group = (Spinner)findViewById(R.id.txtGroup);
        Button cost = (Button)findViewById(R.id.btnCost);
        cost.setOnClickListener(new View.OnClickListener() {
                                    final TextView result = ((TextView)findViewById(R.id.txtResult));

                                    @TargetApi(Build.VERSION_CODES.N)
                                    @Override
                                    public void onClick(View v) {
                                        numberOfTickets = Integer.parseInt(tickets.getText( ).toString( ));
                                        totalCost = costPerTicket * numberOfTickets;
                                        DecimalFormat currency = new DecimalFormat("$###,###.##");
                                        groupChoice = group.getSelectedItem( ).toString( );
                                        String costForString = "Cost for " + groupChoice + "is " + currency.format(totalCost);
                                        result.setText(costForString);

                                    }
                                }
        );

    }
}