在我的活动中,我有一个ImageView
XML程式码:
<!-- FOTO LATERAL! -->
<ImageView
android:id="@+id/simbolo_raca"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
<Button
android:id="@+id/button_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ok. Seguinte Pergunta"
android:layout_gravity="right"
android:gravity="right"
android:paddingRight="30dip">
</LinearLayout>
这是活动:
public class QuestionarioActivityRaca extends Activity{ ImageView simbolo; int position; Button B_Save; List<Drawable> List_imagens = new ArrayList<Drawable>(); @Override public void onCreate(Bundle savedInstanceState) { simbolo = (ImageView) findViewById(R.id.simbolo_raca); B_Save = (Button) findViewById(R.id.button_save); position = 0; List_imagens.add(getResources().getDrawable(R.drawable.p1)); List_imagens.add(getResources().getDrawable(R.drawable.p2)); List_imagens.add(getResources().getDrawable(R.drawable.p3)); List_imagens.add(getResources().getDrawable(R.drawable.p4)); loadNewImage(position); B_Save.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { loadNewImage(position); position++; } }); } // I Use this method to load the Image public loadNewImage(int Page) { new Thread(new Runnable(){ @Override public void run(){ simbolo.post(new Runnable(){ @Override public void run() { simbolo.setImageDrawable(List_imagens.get(Page)); } }); } }).start(); }
我第一次调用此方法时,(位置= 0)图像未加载。之后,图像将正确加载。
第一次如何加载图像?
(我无法使用来将图片加载到XML中android:src="@drawable/x"
),因为图片随时都可能不同。编辑!
您发布的代码示例存在许多问题。
就像用大写I编写int一样。
Int position;
没有在onClick中使用您的方法发送参数:
public void onClick(View v) {
loadNewImage();
}
XML和代码中还有更多。
您是否有特殊原因想要每次为此任务运行一个新线程?如果确实需要线程,则必须在方法中将int声明为final。
但是,您应该使用下面的代码示例获得所需的结果。您必须修改onClick才能为要使用的任何可绘制对象发送适当的int。
祝你好运。
public class testactivity extends ActionBarActivity {
ImageView simbolo;
int position;
Button B_Save;
List<Drawable> List_imagens = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_testactivity);
simbolo = (ImageView) findViewById(R.id.simbolo_raca);
B_Save = (Button) findViewById(R.id.button_save);
position = 0;
List_imagens.add(getResources().getDrawable(R.drawable.ic_drawer));
List_imagens.add(getResources().getDrawable(R.drawable.ic_check));
List_imagens.add(getResources().getDrawable(R.drawable.ic_action_add_package));
List_imagens.add(getResources().getDrawable(R.drawable.ic_action_exception));
loadNewImage(position);
final Random rand = new Random();
B_Save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
loadNewImage(rand.nextInt(4));
}
});
}
public void loadNewImage(final int page)
{
simbolo.setImageDrawable(List_imagens.get(page));
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句