开发者

How to make a single View globally accessible?

Is there any way to make a single View (in this case a TextView) globally accessible? I tried putting the TextView in it's own XML-file, like so:

<!-- File: list_header.xml -->
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/list_header"
    android:layout_width="match_p开发者_C百科arent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium">
</TextView>

However, when trying to access this TextView (using mListHeader = (TextView) findViewById(R.id.list_header)) I receive null.

I think I've seem some example using this approach, so I think it should be possible. If not, I would be happy to get some help in finding out another approach.

Maybe this question should have been labeled otherwise, since my main question is how to solve a specific problem:

The TextView in question is supposed to be used as a header in a ListView. This header will be used in a number of ListViews, so I want to set it's properties using XML. I could put it in the same XML-file as the ListView's, but I don't want the TextView appear in any other way as header for the ListView's. One way to solve the problem would be to put the TextView in it's own XML-file, as I tried to do, but it didn't work.

Now, I'm not sure about the Stack Overflow practice in situations like this, but in any case, I'd like an answer for both questions.


Try using either an <include /> or <merge /> in your layouts to use a single control definition in multiple layouts. There is a tutorial on includes here.


Inflate the view and add it as a header in the ListView:

  View header = getLayoutInflater().inflate(R.layout.list_header, null);
  list.addHeaderView(header);
  BaseAdapter adapter = getAdapter(); 
  list.setAdapter(adapter); //the header view must be added before you set the adapter


You're getting null because a View with the ID you are trying to find is not in the view hierarchy you set with setContentView.

You therefore have two options:

  1. Use an <include /> tag to include the layout you want into the larger layouts you set with setContentView
  2. Use a LayoutInflater to inflate the View and add it to the existing view hierarchy created in setContentView

Making a View object itself (not the layout) globally accessible, i.e. by putting it in a static field, will cause memory leaks.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜