字符串未传入' setText()' android中的方法?

时间:2015-10-20 14:02:15

标签: android string

问题出在setText()行中。我从意图中获取字符串,它单独显示但不显示在%s选项中。这是我的代码:

package com.example.roa.gimatryapp2;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class Result extends AppCompatActivity {

    private TextView resultText;
    private Button restartButton;
    private String mName;   //strinh name
    private int count;
    private ColorWheel mColorWheel = new ColorWheel();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);

        final RelativeLayout relativeLayout = (RelativeLayout)findViewById(R.id.relativeLayout);
        resultText = (TextView)findViewById(R.id.resultText);
        restartButton = (Button)findViewById(R.id.restartButton);

        int color = mColorWheel.getColor();
        int color2 = mColorWheel.getColor();

        relativeLayout.setBackgroundColor(color);
        restartButton.setBackgroundColor(color2);
        if(color == color2){
            restartButton.setBackgroundColor(color2);

        }

        Intent intent = getIntent();
        mName = intent.getStringExtra("username");    //get the string from the intent
        count = intent.getIntExtra("result", count);


        resultText.setText("Hi %s , you have a grate name your name is equal to: ", mName + count);  //here is the problam. if it is like ("..." + mName)it show up

    }
}

感谢。

2 个答案:

答案 0 :(得分:0)

可以使用您之前intent.putExtra("username");使用过的Avtivity因此,您必须在String这样的内容中获得Activity

Bundle extras = getIntent().getExtras();
if(extras !=null) {
    mName = extras.getString("username");
}

希望它有所帮助。

答案 1 :(得分:0)

TextView没有setText()方法,该方法读取格式化args。您需要传递一个已经格式化的String(或其他CharSequence)。对于带有原始String的用例,这类似于

resultText.setText(String.format("Hi %s , you have a grate name your name is equal to: ", mName + count));

更常见的是,您在xml资源中定义了一个String,并且您将使用

resultText.setText(getResources().getString(R.string.string_name, mName + count));