【问题标题】:Adding Android buttons to view dynamically添加Android按钮以动态查看
【发布时间】:2015-06-23 08:08:07
【问题描述】:

我已经看过以下问题和一堆其他问题:How to add a button dynamically in Android?

Dynamically Creating/Removing Buttons in Android

我有 2 个带有片段的活动。每次用户在第二个活动上按下一个按钮时,他们都会被重定向到主要活动,并且一个按钮被添加到页面中。尽管按钮已正确保存在 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:

<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 片段 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>

新创意按钮将他们带到第二个活动,在那里他们创建添加到主活动的按钮。知道为什么实际上只显示最近的按钮吗?调试时所有的按钮都会显示在想法数组中。

【问题讨论】:

  • 如果您有多个按钮,您应该考虑使用列表视图。它是为这些东西而设计的。
  • @ElDuderino 我现在正在调查这个。好像有很多,没有更简单的方法吗?我的方法有什么问题?
  • 我刚刚在我的回答中添加了一些关于 listview 教程的提示,

标签: java android button android-fragments


【解决方案1】:

您有一个 RelativeLayout 作为父级。这意味着,你必须告诉孩子们他们应该在哪里,你可以这样做,例如

android:layout_alignParentTop

就像您在 xml 中所做的那样。 (顺便说一句,其中一些对齐会自行抵消)

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

你会发现,还有

android:layout_below

需要一个 ID。

您需要做的是给生成的按钮一个 ID,它可以是一个数字。 然后你必须在你的 RelativeLayout 布局参数中添加一个规则。

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

并删除那些 setTranslations()。

但是,如前所述,请查看 ListView(或新的 RecyclerView)。

如果您查看教程,请不要在http://developer.android.com/guide/topics/ui/layout/listview.html 上这样做,这不是好的开始。试试这个http://windrealm.org/tutorials/android/android-listview.php。只需将行星数组与您的想法数组和 textview xml 与按钮交换即可。它应该可以工作。

编辑:

试试这个,它有效。

@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);

    }
}

【讨论】:

  • 在设置参数并将其添加到布局之前,我在 if stmnt 中添加了这两行。我使用 .setId() 将 ID 设置为 idea.size()。问题仍然存在。我会尝试 ListView(感谢 tut),但我想知道我当前的代码有什么问题。
  • 我尝试了您的代码并且它有效,但是当我将概念转换为我的代码时,我遇到了同样的问题。我更新了我的 MainActivity 代码以向您展示我做了什么。我现在没有使用片段,所以我也重新制作了 onCreate 中的新创意按钮。
  • 像我使用 ID+X 一样进行操作,例如 1000 在我的情况下,因为 0 不是有效的 ID,您可以在此处阅读 developer.android.com/reference/android/content/res/…。 newIdea 按钮什么也不做。你不需要 settranslation。
  • 我把所有的ideas.size()都换成了ideas.size() + 1000,没有任何变化。我需要 newIdea 按钮将我带到可以制作按钮的其他活动。基本上每次我单击 newIdea 按钮,然后单击另一个活动上的返回按钮时,我都会在意图中传递一个标题,每当我回到 MainAcitivity 时,应该使用新按钮创建该标题。它被翻译为与动态创建的按钮重叠的临时修复。
【解决方案2】:

每次 onCreate() 被调用,特别是当 setContentView() 被调用时,你的整个布局都会被清空并加载 R.layout.activity_main。

您只看到最近的按钮的原因是因为您最多只在 onCreate() 中添加了一个按钮。按钮的位置是偏移的,因为您正在根据您的想法数组中的按钮数量计算其 y 位置。

我会这样做:

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);
}

【讨论】:

  • 我试过这个。它给了我这个错误:“java.lang.IllegalStateException:指定的孩子已经有一个父母。你必须先在孩子的父母上调用removeView()”,我认为这意味着我正在向多个视图添加相同的按钮次。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-24
相关资源
最近更新 更多