简体   繁体   English

在Android中以编程方式添加视图

[英]Adding views programmatically in Android

Is it possible to add views to a different layout than the one called in setContentView() in the OnCreate()? 是否可以将视图添加到与OnCreate()中的setContentView()中调用的布局不同的布局?

Im trying to use Zylincs ViewPager (found at http://www.zylinc.com/blog-reader/items/viewpager-page-indicator.html ) and I have that part setup and working great. 我试图使用Zylincs ViewPager(在http://www.zylinc.com/blog-reader/items/viewpager-page-indicator.html上找到),我有那个部分设置并且工作得很好。

What this leaves me with is 4 layouts. 这给我留下了4个布局。 1 is main.xml, and the other three are main_pg0.xml, main_pg1.xml, and main_pg3.xml 1是main.xml,其他三个是main_pg0.xml,main_pg1.xml和main_pg3.xml

The three pages are where the content of each "page" is where main.xml contains the page viewer. 这三个页面是每个“页面”的内容所在的位置,其中main.xml包含页面查看器。

In the onCreate im using setContentView(main.xml). 在onCreate中使用setContentView(main.xml)。

What im trying to do now is be able to add textViews programically to some of the pages. 我现在尝试做的是能够以编程方式将textViews添加到某些页面。

What I have right now is: 我现在拥有的是:

LayoutInflater factory = getLayoutInflater();

View layout = factory.inflate(R.layout.main_pg0, null);
View linearLayout = layout.findViewById(R.id.linearLayout);

TextView valueTV = new TextView(this);
valueTV.setText("hallo hallo");
valueTV.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));

((LinearLayout) linearLayout).addView(valueTV);

This is as far as I've been able to get, which does not add the textview at all. 这是我能够得到的,它根本不添加textview。

----EDIT---- - - 编辑 - -

Hoping to clarify a little more what im trying to do Heres my code 希望更多地澄清我试图做什么继承我的代码

Main.java Main.java

public class Main extends FragmentActivity implements PageInfoProvider {
  public GlobalVars globalVars;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    globalVars = (GlobalVars) getApplicationContext();

    MyPagerAdapter adapter = new MyPagerAdapter();
    ViewPager myPager = (ViewPager) findViewById(R.id.viewpager);
    myPager.setAdapter(adapter);
    myPager.setCurrentItem(0);

    ViewPagerIndicator indicator = (ViewPagerIndicator) findViewById(R.id.indicator);
    myPager.setOnPageChangeListener(indicator);

    indicator.init(0, adapter.getCount(), this);

    Resources res = getResources();
    Drawable prev = res.getDrawable(R.drawable.indicator_prev_arrow);
    Drawable next = res.getDrawable(R.drawable.indicator_next_arrow);

    indicator.setArrows(prev, next);
  }

  private class MyPagerAdapter extends PagerAdapter {

    public int getCount() {
      return 3;
    }

    public Object instantiateItem(View collection, int position) {

      LayoutInflater inflater = (LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

      int resId = 0;
      switch (position) {
      case 0:
        resId = R.layout.main_pg0;
        LoadVehicles();
        break;
      case 1:
        resId = R.layout.main_pg1;
        break;
      case 2:
        resId = R.layout.main_pg2;
        break;
      }

      View view = inflater.inflate(resId, null);
      ((ViewPager) collection).addView(view, 0);

      return view;
    }

    @Override
    public void destroyItem(View arg0, int arg1, Object arg2) {
      ((ViewPager) arg0).removeView((View) arg2);

    }

    @Override
    public void finishUpdate(View arg0) {
      // TODO Auto-generated method stub
    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
      return arg0 == ((View) arg1);
    }

    @Override
    public void restoreState(Parcelable arg0, ClassLoader arg1) {
      // TODO Auto-generated method stub

    }

    @Override
    public Parcelable saveState() {
      // TODO Auto-generated method stub
      return null;
    }

    @Override
    public void startUpdate(View arg0) {
      // TODO Auto-generated method stub

    }

  }

  public String getTitle(int position) {
    String title = "--Untitled--";
    switch (position) {
    case 0:
      title = "Page 0";
      break;
    case 1:
      title = "Page 1";
      break;
    case 2:
      title = "Page 2";
      break;
    }
    return title;
  }
}

main.xml main.xml中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical" >
  <com.zylinc.view.ViewPagerIndicator
    android:id="@+id/indicator"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#EAEAEA"
    android:paddingBottom="8dp"
    android:paddingLeft="5dp"
    android:paddingRight="5dp"
    android:paddingTop="8dp" />
  <RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#ffeaeaea" >
    <View
      android:layout_width="fill_parent"
      android:layout_height="1dp"
      android:layout_alignBottom="@+id/current"
      android:background="#C5C5C5" />
    <ImageView
      android:id="@+id/current"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentTop="true"
      android:layout_centerInParent="true"
      android:src="@drawable/indicator_current" />
  </RelativeLayout>
  <android.support.v4.view.ViewPager
    android:id="@+android:id/viewpager"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />
</LinearLayout>

main_pg0.xml main_pg0.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:background="#FFFFFF"
  android:orientation="vertical"
  android:id="@+id/linearLayout" >
  <TextView
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:layout_marginLeft="5dp"
      android:text="main_pg0.xml"
      android:textColor="#0C0C0C"
      android:textSize="18sp" />

</LinearLayout>

What im trying to do is add a text view programmatically to main_pg0.xml ONLY, while leaving the other 2 pages alone 我想要做的是以编程方式将文本视图添加到main_pg0.xml,同时仅保留其他2个页面

You have to add view in main view which is inflated layout.So just add one line. 你必须在主视图中添加视图,这是一个膨胀的布局。所以只需添加一行。

LayoutInflater factory = getLayoutInflater();

View layout = factory.inflate(R.layout.main_pg0, null);
View linearLayout = layout.findViewById(R.id.linearLayout);

TextView valueTV = new TextView(this);
valueTV.setText("hallo hallo");
valueTV.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));

((LinearLayout) linearLayout).addView(valueTV);
layout.addView(linearLayout);

You haven't explicitly mentioned whether you're feeding Fragment s to the ViewPager , but since you're working from the Zylinc implementation, I'm going to assume you are. 您还没有明确提到是否要将FragmentViewPager ,但是由于您正在使用Zylinc实现,我将假设您是。 As a matter of fact, I'll just use the provided example code to show you the idea. 事实上,我只是使用提供的示例代码向您展示这个想法。

The key to understanding how to realise what you're after is to get that the pages in the ViewPager are self-contained units in the form of Fragment s. 了解如何实现您所追求的目标的关键是使ViewPager中的页面成为Fragment形式的自包含单元。 They are reusable, have their own life cycle, and can handle their own layouts. 它们是可重用的,有自己的生命周期,可以处理自己的布局。 Hence, if you want to make runtime modifications to the layout of the pages, you will want to do this inside the Fragment (s) that make up these pages. 因此,如果要对页面布局进行运行时修改,则需要在构成这些页面的Fragment内执行此操作。

The following method can be found in the example code's ItemFragment class. 可以在示例代码的ItemFragment类中找到以下方法。 I've simply added the TextView from your own code snippet to it. 我只是将您自己的代码片段中的TextView添加到它。 For demonstration purposes, I did hide the ListView that used to fill up all the space in the date_fragment.xml layout file. 出于演示目的,我确实隐藏了用于填充date_fragment.xml布局文件中所有空间的ListView

@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.date_fragment, container, false);
    View tv = v.findViewById(R.id.text);
    ((TextView)tv).setText(readableDateFormat.format(date));

    // changes below
    TextView valueTV = new TextView(getActivity());
    valueTV.setText("hallo hallo");
    valueTV.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
    ((ViewGroup)v).addView(valueTV);

    return v;
}

That will give you the "hallo hallo" text (you're a Dutchie? ;)) directly underneath the date in the page: 那将直接在页面中的日期下面给你“hallo hallo”文本(你是Dutchie?;)):

代码段的结果

By the way, you might want to consider switching to Jake's ViewPagerIndicator . 顺便说一下,您可能需要考虑切换到Jake的ViewPagerIndicator Although I haven't closely looked at the one you're currently using, Jake's seems more flexible to me and cleaner to work with. 虽然我没有仔细看过你正在使用的那个,但是Jake对我来说似乎更灵活,更清洁。 Up to you of course. 当然是你自己。


Edit: Okay, so you're not actually using fragments in the ViewPager , but are rather feeding it the layouts. 编辑:好的,所以你实际上并没有在ViewPager使用片段,而是在为它提供布局。 That's fine, although it'll probably become harder to manage when the pages get more complex. 这很好,虽然当页面变得更复杂时,管理可能会变得更难。 Anyways, key to changing the page's layouts at runtime is still to do it whenever you build/inflate it. 无论如何,在运行时更改页面布局的关键仍然是在构建/充气时进行。 When using fragments, that would be in the overridden method, as shown above. 使用片段时,这将是重写方法,如上所示。 In your case, however, you'll need to do it directly in instantiateItem(...) . 但是,在您的情况下,您需要直接在instantiateItem(...)

I didn't actually type this out in an IDE, so please mind and minor syntactical errors. 我实际上并没有在IDE中输出这个,所以请注意和轻微的语法错误。

public Object instantiateItem(View collection, int position) {

    LayoutInflater inflater = (LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View view = null;
    switch (position) {
    case 0:
        view = inflater.inflate(R.layout.main_pg0, null);
        TextView valueTV = new TextView(getActivity());
        valueTV.setText("hallo hallo");
        valueTV.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
        ((ViewGroup)view).addView(valueTV);
        break;
    case 1:
        view = inflater.inflate(R.layout.main_pg1, null);
        // or perhaps better for readability: build the layout in a different method, passing in the root
        buildSecondPageLayout(view);
        break;
    case 2:
        view = inflater.inflate(R.layout.main_pg2, null);
        buildThirdPageLayout(view);
        break;
    }

    return view;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM