2011-03-17 57 views
1

好吧,我已经定义喜欢我的main.xml:Android:你可以在代码中编辑用xml创建的视图吗?

<LinearLayout android:id="@+id/linearLayout1" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"> 

    <EditText android:text="EditText" android:id="@+id/editText1" android:layout_width="match_parent" android:layout_height="175px"></EditText> 
    <LinearLayout android:layout_height="wrap_content" android:id="@+id/linearLayout2" android:layout_width="match_parent" android:layout_marginLeft="100px"> 
     <Button android:id="@+id/button1" android:layout_height="wrap_content" android:layout_weight="1" android:layout_width="wrap_content" android:text="@string/btnPrint"></Button> 
     <Button android:id="@+id/button2" android:layout_height="wrap_content" android:layout_weight="1" android:layout_width="wrap_content" android:text="@string/btnCancel"></Button> 
    </LinearLayout> 
</LinearLayout> 

我希望能够调用之前更新从代码的EditText的光标位置setContentView(R.layout.main),这可能吗?如果不是,那么用于设置EditText View的光标位置的xml属性是什么?

感谢,

贾斯汀

回答

0

在setContentView()调用之前,您将无法操作Java视图中的视图,因为findViewById(R.id.yourView)将返回null,除非有问题的视图实际上位于屏幕上。你有没有这样做的理由?

setContentView(R.layout.main); 
EditText et = (EditText)findViewById(R.id.yourEditText); 
et.setSelection(position); 

尽管光标在技术上会在其可见之后移动,但它将会非常快以至于用户不太可能注意到。

+0

我想这样做,我应该这样做,我应该大声笑。我只是新的这个android编程的东西。不习惯整个XML UI编程的东西。 – Justin 2011-03-17 14:49:53

+0

我认为这对你而言会很好。 – FoamyGuy 2011-03-17 14:50:45

+0

我还有一个问题,不妨在这里问一下。我正在通过手机调试我的程序。现在,我更改了main.xml,但是当程序加载到手机上时,它仍然显示最初在helloworld示例中的布局。 – Justin 2011-03-17 15:03:26

2

你不能做的意见,这是尚未膨胀的任何修改。所以,第一个答案是

至于第二个尝试这个标签<requestFocus />您编辑文本中:

<EditText ...> 
    <requestFocus /> 
<EditText/> 
+0

我猜'膨胀'意味着在屏幕上(在布局中)创建和可见。我会尝试requestFocus标记并查看会发生什么,谢谢。 – Justin 2011-03-17 14:52:44

0

充气的观点,然后将光标位置或进行所需的任何更改,然后设置通过这个视图的setContentView()方法。

+0

好的。谢谢 – Justin 2011-03-17 14:53:44