【发布时间】:2015-10-20 22:15:06
【问题描述】:
在阅读了一些相关帖子后,我已经知道在尝试通过 id 将元素查找到 Activity-View-Hierarchy 之前,我必须显式调用 setContenView。我创建了一个带有膨胀视图的 Activity 并且一切正常。问题是当我尝试使用下一个 xml 和代码为该活动设置另一个视图时:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="0dp"
android:paddingRight="0dp"
android:paddingTop="0dp"
android:paddingBottom="0dp"
android:background="#B12A6D"
tools:context=".MainActivity"
android:orientation="vertical"
>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="top"
android:background="@drawable/bg_purple_500"
android:layout_margin="0dp"
>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/GridLayout1"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="50"
android:columnCount="4"
android:rowCount="4"
android:orientation="horizontal"
tools:context=".GridXMLActivity"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
>
<ImageView
android:id="@+id/my_bnt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/icon_new_game"
android:contentDescription="@string/text"
android:layout_marginTop="10dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="10dp"
/>
</GridLayout>
</LinearLayout>
</RelativeLayout>
代码:
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
....
protected void method_triggered_from_UI_thread() {
// Inflate other layout...
View view = View.inflate(this, R.layout.my_layout, null) ;
setContentView(view);
ImageView btn = (ImageView) findViewById(R.id.my_bnt);
// btn is null...
}
我尝试了其他细微的变化:
View mainView = findViewById(android.R.id.content);
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.my_layout, (ViewGroup) mainView, false) ;
setContentView(view);
ImageView btn = (ImageView) view.findViewById(R.id.my_bnt);
而且我总是得到 btn == null。我做错了什么?
谢谢
【问题讨论】:
-
ImageView btn = (ImageView) view.findViewById(R.id.my_bnt);第一种情况 -
my_layout 是否有 ID 为 my_bnt 的 thr 按钮?
-
mainView是什么? -
尝试使用
new LinearLayout(mainActivity)而不是(ViewGroup) mainView作为第二个参数 -
你能发布你的全部java代码吗?
标签: android