问题描述
我试图让一个ImageView的对象,不管出于什么原因,它让回来为空的参考。
I'm trying to get a reference to an ImageView object and for whatever reason, it keeps coming back as null.
XML:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="6dip">
<ImageView android:id="@+id/application_icon" android:layout_width="wrap_content" android:layout_height="wrap_content" />
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/label" android:text="Application Name" />
<CheckBox android:id="@+id/check" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right" />
</LinearLayout>
Java的:
ImageView img = (ImageView) v.findViewById(R.id.application_icon);
我不觉得我做错什么但我的IMG变种总是回来空。什么是不对的图片?
I don't feel like I'm doing anything wrong yet my img var always comes back as null. What's wrong with this picture?
推荐答案
周六的答案是正确的,也就是说,你需要一个适当的布局,但的setContentView()
是不是引用的视图的唯一途径。您可以使用膨胀的查看
(即使没有示出)的母体布局和使用新充气布局引用视图。
Sat's answer is correct, i.e., you need a proper layout, but setContentView()
is not the only way to reference a View. You can use a LayoutInflater
to inflate a parent layout of the View
(even if it is not shown) and use that newly inflated layout to reference the View.
public class MyActivity extends Activity {
Context context;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
// the rest of yout code
private void someCallback() {
LayoutInflater inflater = (LayoutInflater) context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout ll = (LinearLayout) inflater.inflate(R.layout.iconLayout, null);
ImageView img = (ImageView) ll.findViewById(R.id.application_icon);
// you can do whatever you need with the img (get the Bitmap, maybe?)
您需要将您的XML文件中唯一的变化是一个ID添加到父布局,所以你可以使用它 LayoutInflater
:
The only change you need to your xml file is to add an ID to the parent layout, so you can use it with the LayoutInflater
:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="iconLayout"
<!-- all the rest of your layout -->
<ImageView android:id="@+id/application_icon" android:layout_width="wrap_content" android:layout_height="wrap_content" />
<!-- all the rest of your layout -->
</LinearLayout>
这篇关于空ImageView的参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!