2013-08-29 3 views
16

Я написал свой собственный вид, и я хочу обновить некоторые другие представления после взаимодействия с моим пользовательским представлением.Android findViewById() в пользовательском представлении

Главная Схема:

<?xml version="1.0" encoding="utf-8"?> 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:custom="http://schemas.android.com/apk/res-auto" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <EditText 
     android:id="@+id/display_name" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:inputType="text" 
     android:layout_centerHorizontal="true" 
     android:tag="name" 
     android:ems="10" /> 

    <EditText 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:inputType="number" 
     android:ems="10" 
     android:id="@+id/id_number" 
     android:layout_centerHorizontal="true" 
     android:layout_below="@id/display_name"/> 

    <ge.altasoft.custom_views.IdNumber 
     android:id="@+id/custom_id_number" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_centerHorizontal="true" 
     android:layout_below="@id/id_number" 
     android:paddingLeft="35dip" 
     custom:firstName="@id/display_name"/> 
</RelativeLayout> 

пользовательский вид макета:

<?xml version="1.0" encoding="utf-8"?> 

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"> 

    <EditText 
     android:id="@+id/id_number_custom" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:inputType="number" 
     android:ems="10" 
     android:paddingRight="35dip" /> 

    <ImageButton 
     android:id="@+id/load_data_button" 
     android:layout_width="30dip" 
     android:layout_height="30dip" 
     android:layout_centerVertical="true" 
     android:src="@drawable/load_data" 
     android:layout_toRightOf="@id/id_number_custom" /> 

</RelativeLayout> 

пользовательский вид класса, конструктор и слушатель:

private int firstNameViewID; 

public IdNumber (Context context, AttributeSet attrs) { 
     super(context, attrs); 
     initViews(); 

     TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.IdNumber); 
     final int N = a.getIndexCount(); 
     for(int i = 0; i < N; i++){ 
      int attr = a.getIndex(i); 
      switch(attr){ 
       case R.styleable.IdNumber_firstName: 
        firstNameViewID = a.getResourceId(attr, -1); 
        break; 
      } 
     } 
     a.recycle(); 
    } 



private void initViews() { 
     inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     inflater.inflate(R.layout.id_number_edit_text_custom, this, true); 
     editText = (EditText) findViewById(R.id.id_number_custom); 
     loadButton = (ImageButton) findViewById(R.id.load_data_button); 
     loadButton.setVisibility(RelativeLayout.INVISIBLE); 
     loadData(); 
    } 

private void loadData(){ 
     loadButton.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       EditText firstName = (EditText) findViewById(R.id.display_name); 
       firstName.setText("Some Text"); 
      } 
     }); 
    } 

Проблема в том, что EditText firstName = (EditText) findViewById(R.id.display_name); возвращает null. Я знаю, что только вызов findViewById() будет искать вид в макете, который я раздул.

Если возможно, как я могу получить представление EditText с id: display_name из основного макета?

Спасибо заранее.

+0

Нет, я не хочу получать свой пользовательский вид, я хочу получить другой вид из mainLayout с id diplay_name. – Jilberta

+0

вы раздуваете xml, но не сохраняете возвращенный вид. вы можете найти представление по id на этом представлении. – Siddhesh

ответ

11
View Custmv; 

private void initViews() { 
     inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     Custmv = inflater.inflate(R.layout.id_number_edit_text_custom, this, true); 
     editText = (EditText) findViewById(R.id.id_number_custom); 
     loadButton = (ImageButton) findViewById(R.id.load_data_button); 
     loadButton.setVisibility(RelativeLayout.INVISIBLE); 
     loadData(); 
    } 

private void loadData(){ 
     loadButton.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       EditText firstName = (EditText) Custmv.getParent().findViewById(R.id.display_name); 
       firstName.setText("Some Text"); 
      } 
     }); 
    } 

попробуйте вот так.

+0

Вы не получили его @Siddesh, editText = (EditText) findViewById (R.id.id_number_custom); loadButton = (ImageButton) findViewById (R.id.load_data_button); это прекрасно работает, я могу просматривать виды из макета CustomView, я хочу получить Views из MainLayout. – Jilberta

+0

нормально, но почему вы хотите обрабатывать основной макет из пользовательского класса вида? – Siddhesh

+0

, потому что я хочу обновить эти представления после взаимодействия с моим пользовательским представлением. – Jilberta

1

Измените метод следующим образом и проверить это будет работать

private void initViews() { 
     inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     inflater.inflate(R.layout.id_number_edit_text_custom, this, true); 
View view = (View) inflater.inflate(R.layout.main, null); 
     editText = (EditText) view.findViewById(R.id.id_number_custom); 
     loadButton = (ImageButton)view. findViewById(R.id.load_data_button); 
     loadButton.setVisibility(RelativeLayout.INVISIBLE); 
     loadData(); 
    } 
+0

Я пробовал этот Усман, но он не работает, представление возвращает null. – Jilberta

+0

Нет необходимости бросать для просмотра, когда LayoutInflater.inflate возвращает View. – vilpe89

0

Если это фиксированный макет можно сделать так:

public void onClick(View v) { 
    ViewGroup parent = (ViewGroup) IdNumber.this.getParent(); 
    EditText firstName = (EditText) parent.findViewById(R.id.display_name); 
    firstName.setText("Some Text"); 
} 

Если вы хотите найти EditText в гибкой планировкой, я буду помогите вам позже. Надеюсь, эта помощь.

+0

parent имеет значение null, если я раздуваю макет, который представляет собой пользовательский вид. – Jilberta

0
@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    View row = convertView; 
    ImageHolder holder = null; 
    if (row == null) { 
     LayoutInflater inflater = ((Activity) context).getLayoutInflater(); 
     row = inflater.inflate(layoutResourceId, parent, false); 
     holder = new ImageHolder(); 
     editText = (EditText) row.findViewById(R.id.id_number_custom); 
     loadButton = (ImageButton) row.findViewById(R.id.load_data_button); 
     row.setTag(holder); 
    } else { 
     holder = (ImageHolder) row.getTag(); 
    } 


    holder.editText.setText("Your Value"); 
    holder.loadButton.setImageBitmap("Your Bitmap Value"); 
    return row; 
} 
+1

Я думаю, что вы отвечаете на другой вопрос. , , – Jilberta

+0

Если вы получите ошибку, как нулевой указатель, чем вы ошибаетесь при инициализации edittext и Imagebutton в соответствии с вашим кодом .... –

+0

нет проблемы нет в editText или в изображенииButton – Jilberta

0

Попробуйте это в конструкторе

MainActivity maniActivity = (MainActivity)context; 
EditText firstName = (EditText) maniActivity.findViewById(R.id.display_name); 
0

Вы можете попробовать что-то вроде этого:

Внутри customview конструктора:

mContext = context; 

Следующая внутри customview вы можете позвонить:

((MainActivity) mContext).updateText(text); 

Внутри MainAcivity определяют:

public void updateText(final String text) { 

    TextView txtView = (TextView) findViewById(R.id.text); 
    txtView.setText(text); 
} 

Это работает для меня.

+0

, вызывающий 'findViewById()' несколько раз плохой и неэффективно. Если вы собираетесь использовать его повторно, сохраните ссылку на него в поле «final». –

Смежные вопросы