Android:你能用代码编辑用xml创建的视图吗?

Android:你能用代码编辑用xml创建的视图吗?,android,Android,好的,我将main.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

好的,我将main.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>

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

谢谢


Justin

您不能对尚未膨胀的视图进行任何修改。因此,第一个答案是否定的

至于第二个,请在编辑文本中尝试此标记

<EditText ...>
  <requestFocus />
<EditText/>


膨胀视图,然后设置光标位置或进行任何更改,然后设置将此视图传递给setContentView()方法。

在调用setContentView()之前,您将无法从java端操作视图,因为findViewById(R.id.yourView)将返回null,除非相关视图实际在屏幕上。你不想这样做有什么原因吗

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

虽然从技术上讲,光标会在其可见后移动,但它的速度将如此之快,以至于用户不太可能注意到。

我想用我想用的任何方式来做。我只是刚刚接触过android编程。我不习惯xml UI编程的所有东西。我还有一个问题,不妨在这里问一下。我正在通过手机调试我的程序。现在,我已经更改了main.xml,但是当程序加载到我的手机上时,它仍然显示最初在helloworld示例中的布局。您是否在手机上安装了新版本?您刚刚编辑了main.xml文件吗?或者您是否创建了一个新的xml文件,如果创建了一个新的xml文件,则必须对该文件调用setContentView(),而不是main。您是否有多个布局文件夹?比如布局mdpi、布局hdpi等?如果是这样,您将不得不更改设备所属的main.xml类别,以反映设备上的更改。我删除了已安装的main.xml,并再次单击eclipse IDE中的“运行”按钮,但它似乎安装了旧的main.xml:(.是的,我编辑的是main.xml,res/layout中没有其他xml文件。没有一个布局文件夹叫做“layout”。再次感谢JustinOk,我找到了它。我走到实际的目录,查看了xml文件,其中只包含了。所以我删除了它,然后在eclipse中对main.xml进行了更改,然后保存了它,并他在设备上做了如下更改:)。感谢您的帮助!我猜“充气”意味着在屏幕上(布局中)创建并可见。我将尝试requestFocus标记,看看会发生什么,谢谢。