为什么这不起作用?
public class MainActivity extends Activity {
Button[] b = null;
Intent[] intent=null;
Class[] klasa;
Typeface font;
TextView glavninaslov;
ImageView plavi,ljubicasti;
AnimationDrawable plavian,ljubicastian;
String[] naslovi;
int i=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] naslovi = {"","First","Second","Third","Fourth","Fifth"};
font = Typeface.createFromAsset(getAssets(),"FatMarker.ttf");
b = new Button[]
{
( Button ) findViewById(R.id.button1),
( Button ) findViewById(R.id.button2),
( Button ) findViewById(R.id.button3),
( Button ) findViewById(R.id.button4),
( Button ) findViewById(R.id.button5),
};
for(i=1;i<6;i++)
{
klasa[i]=Class.forName(naslovi[i]);//Problem is in:"Class not found exception"
intent[i] = new Intent(MainActivity.this,klasa[i]);
b[i].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v)
{
startActivity(intent[i]);
gasenje();
}
});
}
任何人都可以帮助我......? 有没有人有类似的问题? 请帮我... 其余的代码不能影响程序...请帮助我...我会很感激...
我已经更新了我的代码...它开始主动,但是当我点击某个按钮时它会破坏应用... Button [] b = null; Intent [] intent = null; 字体字体; TextView glavninaslov; ImageView plavi,ljubicasti; AnimationDrawable plavian,ljubicastian;
int i=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Class[] naslovi = {
First.class,
Second.class,
Third.class,
Fourth.class,
Fifth.class};
font = Typeface.createFromAsset(getAssets(),"FatMarker.ttf");
b = new Button[]
{
( Button ) findViewById(R.id.button1),
( Button ) findViewById(R.id.button2),
( Button ) findViewById(R.id.button3),
( Button ) findViewById(R.id.button4),
( Button ) findViewById(R.id.button5),
};
intent = new Intent[b.length];
for(i=0;i<5;i++)
{
intent[i] = new Intent(MainActivity.this,naslovi[i]);
b[i].setTag(i);
b[i].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v)
{
startActivity(intent[(Integer)v.getTag()]);
gasenje();
}
});
}
此代码有效......谢谢你们
答案 0 :(得分:2)
而不是像你一样使用反射创建这些类,正如kcoppock建议你应该这样做:
Class[] naslovi = {
First.class,
Second.class,
Third.class,
Fourth.class,
Fifth.class};
然后在你的循环中:
intent[i] = new Intent(MainActivity.this, naslovi[i]);
假设您有一个名为First
,Second
等的类,则需要包含包名称:
String[] naslovi = {"",
"com.package.First",
"com.package.Second",
"com.package.Third",
"com.package.Fourth",
"com.package.Fifth"};
将com.package
替换为每个类的包。
此外,在你解决了这个问题之后,我预计你会得到IndexOutOfBoundsException
- 删除空白&#34;&#34;来自naslovi
的元素,并将您的for
循环更改为for(i=0;i<5;i++)
答案 1 :(得分:1)
问题是i
执行OnClickListener
时不会保留当前值。您可以使用按钮的标签值来保留正确的值。
for (int i=0; i<b.length; i++) {
//existing logic
b[i].setTag(i);
b[i].setOnClickListener(new OnClickListener() {
public void onClick(View view) {
startActivity(intent[(Integer)view.getTag()]);
}
});
}