2013-12-11 45 views
0

我刚开始开发一个android应用程序。而这个应用程序只是一个随机报价应用程序。 现在我试图从随机引用textview中获取文本。但它返回false。如何从随机设置textview中获取文本?

public class DisplayQuoteActivity extends Activity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_display_quote); 

    final String[] listQuotes = {"Quote one","A million or so","Really don't care","Looks like it","Day is done!"}; 

    Random randGen = new Random(); 
    int rando = randGen.nextInt(5); 

    TextView textQuote = (TextView) findViewById(R.id.viewQuote); 
    textQuote.setText(listQuotes[rando]); 
} 


/** Called when an user wants to share a quote**/ 
public void shareQuote(View view){ 
    Log.d("test_app","Share Quote been pushed"); 
    Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND); 
    sharingIntent.setType("text/plain"); 
    String shareBody = this.getString(R.id.viewQuote);// "Here is the share content body"; 
    sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here"); 
    sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody); 
    startActivity(Intent.createChooser(sharingIntent, "Share via")); 
} 

}

shareBody似乎是假的。

如何从textview viewQuote获取文本?

回答

1

textQuote一个全局变量和替换

String shareBody = this.getString(R.id.viewQuote); 

String shareBody = textQuote.getText().toString(); 
+0

TX,提出您的建议通过工作'字符串shareBody = textQuote.getText()的toString();',使textQuote一个全局变量 – alex

+0

欢迎您。如果这有助于你接受答案。 – Apoorv

+0

顺便说一句,你有什么建议采取哪种策略来结合500个不同的报价和每周增加的报价?我应该使用文本文件还是数据库?在此先感谢 – alex

1

尝试这样做:

String shareBody = ((TextView) findViewById(R.id.viewQuote)).getText(); 
+0

对不起,你的建议给出了这个消息:'错配:不能从CharSequence转换为字符串' – alex

+1

是的,对..你需要做textView.getText()。toString()。我忘了那个。基本上,characterSequence是String实现的接口。父母与孩子的绑定问题。 –

1

使用简单,就是一个

textQuote.getText().toString(); 

((TextView) findViewById(R.id.viewQuote)).getText().toString(); 
+0

thx您的建议也适用。但作为一个noob,你会推荐你的或Apoorv通过使textQuote成为全球性的解决方案? – alex

+0

取决于您访问“TextView”的次数。如果你不止一次访问它:而是增加一个全局的'textQuote'/String字段作为_Apoorv_提议。如果你只访问一次,我的上面也不错。如果您熟悉Java和注释,AndroidAnnotations(http://androidannotations.org/)可能会对您有所帮助。 – Trinimon

相关问题