简体   繁体   English

添加Android按钮以动态查看

[英]Adding Android buttons to view dynamically

I have already looked at the following questions and a bunch of other ones: How to add a button dynamically in Android? 我已经看过以下问题以及其他问题: 如何在Android中动态添加按钮?

Dynamically Creating/Removing Buttons in Android 在Android中动态创建/删除按钮

I have 2 activities with a fragment. 我有2个活动片段。 Each time the user presses a button on the second activity they get redirected to the main activity and a button is added to the page. 每次用户在第二个活动上按下按钮时,他们将被重定向到主活动,并且按钮将添加到页面中。 Even though the buttons are being saved properly in MainActivity in an array only the most recent one is shown on the layout, but it is being pushed downward as if the other ones are above it. 即使将按钮正确地保存在MainActivity中的数组中,布局中也仅显示最新的按钮,但是将按钮向下推,就像其他按钮在其上方一样。

In MainActivity: 在MainActivity中:

private static List<Button> ideas = new ArrayList<Button>();
private static SharedPreferences sharedPref;
private Context myContext;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    RelativeLayout layout = new RelativeLayout(this);
    setContentView(layout, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    Intent intent = getIntent();

    Button newIdea = new Button(this);
    newIdea.setText("NEW IDEA");
    newIdea.setTranslationX(300);
    newIdea.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(v.getContext(), NewIdeaPageActivity.class);
            startActivity(intent);
        }
    });
    layout.addView(newIdea);


    if (intent != null) {
        if (intent.hasExtra("title")) {
            Button button = new Button(this);
            button.setId(ideas.size());
            button.setText(getIntent().getStringExtra("title"));
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

            if (ideas.size() == 0) {
                params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
            } else {
                params.addRule(RelativeLayout.BELOW, ideas.size() - 1);
            }
            layout.addView(button, params);
            ideas.add(button);
        }
    }
}

MainActivity xml: MainActivity xml:

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:id="@+id/fragment"
    android:name="com.zarwanhashem.ideatrackr.MainActivityFragment"
    tools:layout="@layout/fragment_main" android:layout_width="match_parent"
    android:layout_height="match_parent" />

MainActivity fragment xml MainActivity片段xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivityFragment"
    android:id="@+id/fragment_main_layout">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Idea"
        android:id="@+id/new_idea_button"
        android:onClick="onNewIdeaButtonClicked"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />
</RelativeLayout>

The new idea button takes them to the second activity where they create the button which is added to the main activity. 新的想法按钮将他们带到第二个活动,在此他们创建添加到主要活动的按钮。 Any idea why only the most recent button is actually displayed? 知道为什么实际上只显示最新按钮吗? All the buttons show up in the ideas array when I debug. 调试时,所有按钮都显示在ideas数组中。

You have a RelativeLayout as parent. 您有一个RelativeLayout作为父级。 That means, you have to tell the children where they should be, and you do that with eg 这意味着,您必须告诉孩子们应该在哪里,然后用例如

android:layout_alignParentTop

as you do in your xml. 就像在xml中一样。 (btw some of those aligns cancel themselves out) (顺便说一下,其中一些阵营将自己取消了)

Read http://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html 阅读http://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html

You will find, there is also 您会发现,还有

android:layout_below

which needs an ID. 需要一个ID。

What you have to do, is give your generated buttons an ID, that can be a number. 您要做的就是给您生成的按钮一个ID,可以是一个数字。 Then you have to add a rule to your RelativeLayout layoutparams. 然后,您必须将规则添加到RelativeLayout layoutparams中。

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT)
params.addRule(RelativeLayout.BELOW, IDofPreviousButtonComesInHere);

And remove those setTranslations(). 并删除这些setTranslations()。

But, as said, have a look into ListView (or new RecyclerView). 但是,正如所说的,请看一下ListView(或新的RecyclerView)。

If you have a look at tutorials, don't do that on http://developer.android.com/guide/topics/ui/layout/listview.html , no good start. 如果您看过教程,请不要在http://developer.android.com/guide/topics/ui/layout/listview.html上进行操作 ,否则就没有好的开始。 Try this http://windrealm.org/tutorials/android/android-listview.php . 试试这个http://windrealm.org/tutorials/android/android-listview.php Just exchange the planets array with your ideas array and the textview xml with a button. 只需用一个按钮交换planets数组和您的idea数组以及textview xml。 And it should work. 它应该工作。

Edit: 编辑:

Try this, it works. 试试这个,行得通。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    RelativeLayout layout = new RelativeLayout(this);
    setContentView(layout, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));



    for(int i = 0; i<10; i++) {

        Button button = new Button(this);
        int id = i+1000;
        button.setId(id);
        button.setText("Button " + i);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        if(i==0) {
            params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        } else {
            params.addRule(RelativeLayout.BELOW, id-1);
        }
        layout.addView(button, params);

    }
}

Every time onCreate() is called, specifically when setContentView() is called, your entire layout is wiped clean and loaded with R.layout.activity_main. 每次调用onCreate()时,特别是在调用setContentView()时,整个布局都会被清除干净,并使用R.layout.activity_main加载。

The reason that you only see the most recent button, is because you are only adding at most one button inside of onCreate(). 之所以只看到最新的按钮,是因为您只在onCreate()中最多添加了一个按钮。 The button's position is offset because you are calculating its y position based on the number of buttons in your ideas array. 该按钮的位置是偏移的,因为您是根据想法数组中按钮的数量来计算其y位置的。

I would do something like this: 我会做这样的事情:

if (intent != null) {
     if (intent.hasExtra("title")) {
        ideas.add(new Button(myContext));
        ideas.get(ideas.size() - 1).setLayoutParams(new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT));
        ideas.get(ideas.size() - 1).setTranslationY(ideas.size() * 100 + 100);
        ideas.get(ideas.size() - 1).setText(intent.getStringExtra("title"));
    }
}

// add all the buttons to the layout hierarchy
for (Button b : ideas) {
    layout.addView(b);
}

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

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