关于ui作业8-4的几个问题
来源:8-4 作业题
我只是傻了三分钟
2019-05-08 23:59:19
1,为什么我在我的ide里编程findeViewByid前不需要加转型?加了转型后反而是灰色的转型词
public class MainActivity extends AppCompatActivity {
private ToggleButton button;
private LinearLayout radioline;
private LinearLayout textL;
private RadioGroup radioButtongroup;
private ImageView img;
private TextView timetext;
private String nowTime;
public void intview() {
button = findViewById(R.id.togglewifi);
radioline = findViewById(R.id.buttonl);
textL = findViewById(R.id.textl);
radioButtongroup = findViewById(R.id.radiogroup);
img = findViewById(R.id.img);
timetext = findViewById(R.id.showtime);
timetext.setText(timetext.getText() + this.nowTime);
}
2,上面代码里的timetext总是会有一个反色提示,提示语为Field can be converted to local varible.....,其他的都没有 就这个有为什么?
3,我在代码里点击button切换img时候,传了一个字符串
switch (checkedId) {
case R.id.meetingb:
img.setImageResource(getResId("meeting",R.drawable.class));
break;
case R.id.officeb:
img.setImageResource(getResId("office",R.drawable.class));
break;
case R.id.visitorb:
img.setImageResource(getResId("visitor",R.drawable.class));
break;
default:
break;
}
然后,我找了了一个方法getResId()将字符串转为资源id,但是网上的这个方法没有看懂,
public static int getResId(String variableName, Class<?> c) {
try {
Field idField = c.getDeclaredField(variableName);
return idField.getInt(idField);
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
现在的c我知道是传入的R.drawable.class类,但是怎么点击上面的R.drawable.class,怎么都跳转不到类里面去,我想看看getDeclaredField()方法是个什么东西,为什么跳不进去呢?
还有,这个方法什么意思,请老师帮忙解释下
2回答
我只是傻了三分钟
提问者
2019-05-09
好,谢谢 那点击R.drawable.class为什么跳转不到源码里去,这个怎么办
irista23
2019-05-09
1、因为Android 从 API 26 之后,使用findViewById()方法 可以直接写为 tv =findViewById(R.id.textView)。
2、as检测到这个变量可以使用局部变量替换,建议你写成局部变量,如果你想消除警告可以直接删除这个变量,在使用的地方直接声明和实例化就可以了。别的没有,可能有多处使用。
3、点击图片切换时可以直接写 img.setImageResource(R.drawable.xxx);这里不需要再通过getResId取得资源id了。getResId()是通过反射的技术获取id,并不常用一般工具类打成.jar包的时候会用到。
相似问题