![](/img/trans.png)
[英]How to import key-value pair String array from strings.xml into TextView using Java Code
[英]Error setting text to a textView from strings.xml via java code
我只想使用Java代碼在strings.xml中的textView中設置文本,但是我做不到,eclipse給了我這個錯誤:“無法解析textView1”和“無法解析textView2”。
這是mi活動:
package com.example.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
public class Descripcion extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.descripcion);
Intent i = getIntent();
int position = i.getExtras().getInt("id");
ImageAdapter imageAdapter = new ImageAdapter(this);
switch (position){
case 0:
ImageView imageView0 = (ImageView) findViewById(R.id.full_image_view);
imageView0.setImageResource(imageAdapter.mThumbIds[position]);
textView1.setText(this,getString(R.string.case0));
textView2.setText(this,getString(R.string.case0b));
break;
case 1:
ImageView imageView1 = (ImageView) findViewById(R.id.full_image_view);
imageView1.setImageResource(imageAdapter.mThumbIds[position]);
textView1.setText(this,getString(R.string.case1));
textView2.setText(this,getString(R.string.case0b));
break;
}
}
}
我一直在尋找解決方案大約3個小時,但我無法解決。
我看不到您在哪里聲明TextView,例如:
TextView textView1 = (TextView)findViewById(R.id.textView1);
1)您沒有定義TextView
2)您沒有執行findViewById
來獲取相應的TextView
怎么做?
您的代碼本身具有有關如何執行此操作的線索,例如:
ImageView imageView1 = (ImageView) findViewById(R.id.full_image_view);
在這里,您定義了ImageView
並將其指向在R.id.full_image_view
定義的layout.xml
這樣,您需要獲取TextView
,例如:
TextView textView1 = (TextView)findViewById(R.id.textView1);
您忘記定義變量textView1
和textView2
。 除此之外,您還需要使用findViewById
獲得對它們的引用。 奇怪的是,您對imageView1
做了此操作,卻忘記了對TextViews
進行了此操作。
在etContentView(R.layout.descripcion)
下面添加以下代碼:
TextView textView1 = (TextView) findViewById(<<-- the id of textView1 -->>); TextView textView1 = (TextView) findViewById(<<-- the id of textView2 -->>);
這是因為未定義textView1和textView2。
您看到使用ImageView做什么了嗎?
ImageView imageView0 = (ImageView) findViewById(R.id.full_image_view);
您必須將相同的概念應用於文本視圖。
TextView textView1 = (TextView) findViewById(R.id.id_of_text_view_1);
TextView textView2 = (TextView) findViewById(R.id.id_of_text_view_2);
然后,您可以在該文本視圖上執行操作,例如設置文本!
定義textview就像定義imageview一樣。
您可以使用
TextView textView1 = (TextView)findViewById(R.id.textView1);
TextView textView2 = (TextView)findViewById(R.id.textView2);
哪里
R.id.textView1
是XML布局中textview1的ID
R.id.textVie2
是XML布局中textview2的ID
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.