Problem:String array set on TextView
I want to change text from the textview when I was click the next button. I have try this code but could not get right direction. would you please fix it.
public class StringTestActivity extends ListActivity {
TextView t;
int count=0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t=(TextView)findViewById(R.id.text);
Resources res = this.getResources();
final String[] capital = res.getStringArray(R.array.Cap);
//ArrayAdapter<S开发者_开发百科tring> n=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,capital);
//setListAdapter(n);
Button next=(Button)findViewById(R.id.btnNext);
next.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(count<capital.length-1)
t.setText(capital[count]);
count++;
}
});
} }
Edit: I have faced this error message.
again edited: main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="@+id/list" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:hint="text" />
<Button android:text="Next" android:id="@+id/btnNext"
android:layout_width="wrap_content" android:layout_height="wrap_content"> </Button>
</LinearLayout>
res/string/array.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="Cap">
<item>A</item>
<item>B</item>
<item>C</item>
<item>D</item>
</string-array>
</resources>
Button btn1;
String countires[];
int i=0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.prob2);
btn1 = (Button) findViewById(R.id.prob2_btn1);
countires = getResources().getStringArray(R.array.country);
for (String string : countires)
{
Log.i("--: VALUE :--","string = "+string);
}
btn1.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
String country = countires[i];
btn1.setText(country);
i++;
if(i==countires.length)
i=0;
}
});
}
If you are not using ListView then implement Activity not ListActivity. So make this change
public class StringTestActivity extends Activity {
Also import android.app.Activity
@Override
public void onClick(View v) {
t.setText(capital[count]);
count++;
count=count%capital.length;
}
Your code looks ok, what do you mean by "could not get right direction"? Does it crash with an exception, does the code never change?
By the way, considering your button is called next, you may want to rewrite it like this:
Override
public void onClick(View v) {
count++;
if( count < capital.length ) // no - 1
{
t.setText(capital[count]);
} else {
/* perhaps v.setEnabled(false); ? */
}
}
精彩评论