如何在对话框中获取动态加载(setView)布局的元素(findViewById)?

时间:2012-04-25 10:01:02

标签: android android-layout android-edittext preferenceactivity

我需要获取在xml布局中定义的EditText,该布局在首选项对话框中作为视图动态加载,即:

public class ReportBugPreference extends EditTextPreference {

    @Override
    protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
        super.onPrepareDialogBuilder(builder);   
        builder.setView(LayoutInflater.from(ctx).inflate(R.layout.preference_report_bug_layout,null));
        EditText edttxtBugDesc = (EditText) findViewById(R.id.bug_description_edittext); // NOT WORKING
    }

}
jjnFord

编辑:解决方案
@Override
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
    super.onPrepareDialogBuilder(builder);  

    View viewBugReport = LayoutInflater.from(ctx).inflate(R.layout.preference_report_bug,null);
    EditText edttxtBugDesc = (EditText) viewBugReport.findViewById(R.id.bug_description_edittext);

    builder.setView(viewBugReport);



}

2 个答案:

答案 0 :(得分:19)

由于您正在扩展EditTextPreference,因此您只需使用getEditText()方法来获取默认文本视图。但是,由于您正在设置自己的布局,这可能无法满足您的需求。

在您的情况下,您应该将XML布局膨胀为View对象,然后在视图中找到editText - 然后您可以将视图传递给构建器。没试过这个,但只是查看你的代码,我认为这是可能的。

这样的事情:

View view = (View) LayoutInflater.from(ctx).inflate(R.layout.preference_report_bug_layout, null);
EditText editText = view.findViewById(R.id.bug_description_edittext);
builder.setView(view);

答案 1 :(得分:9)

  

需要LayoutInflater来创建(或填充)基于XML文件的View   运行。例如,如果您需要动态生成视图   你的ListView项目。   What is the layout inflater in an Android application?

  1. 创建LayoutInflater:
  2. LayoutInflater inflater = getActivity().getLayoutInflater();

    1. 由inflater创建您的视图,参考your_xml_file:
    2. View view= inflater.inflate(R.layout.your_xml_file, null);

      1. 通过ID在您的布局中找到您的对象。
      2. TextView textView = (TextView)view.findViewById(R.id.text_view_id_in_your_xml_file);

        1. 使用您的对象:即。
        2. textView.setText("Hello!");