【问题标题】:How to add a button programmatically to a fragment如何以编程方式将按钮添加到片段
【发布时间】:2014-07-17 15:40:41
【问题描述】:

我无法以编程方式将按钮添加到片段。 (按钮数量可变)

我尝试使用“an”addView 方法将按钮添加到 rootView,但没有。

我尝试在膨胀之前将按钮添加到布局中,但我不知道如何获取布局:(类型 id 错误的预期资源)

RelativeLayout rl = getView().findViewById(R.layout.fragment_main);

但是当inflater给它充气时,资源是好的。

我尝试在“onViewCreated”方法中添加按钮,但我遇到了同样的问题,findViewById(R.layout.fragment_main) 告诉我有一个错误(类型 id 的预期资源)。

当我创建这样的按钮时:

Button bt = new Button(this);

“this”不是有效的上下文。不知道用什么代替。

那么,我该如何实现呢?

基本代码:

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (savedInstanceState == null) {
        getFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment())
                .commit();
    }
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        return rootView;
    }
}
}

Activity_main.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:ignore="MergeRootFrame" />

Fragment_main.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=".MainActivity$PlaceholderFragment">

    <TextView
        android:text="@string/hello_world"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>

【问题讨论】:

    标签: android android-fragments


    【解决方案1】:

    在您的代码中,fragment_main.xml 中有几处需要更正:

    如果你想访问 xml 中的元素,你需要给它一个唯一的 id。对于您的相对布局,您会丢失它,因此您将无法在片段视图中找到它。

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/fragment_main_layout"     <!--some id-->
        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=".MainActivity$PlaceholderFragment">
    
        <TextView
            android:text="@string/hello_world"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    
    </RelativeLayout>
    

    现在您可以在片段类中找到它!

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
    
        //Find the layout with the id you gave in on the xml
        RelativeLayout rl = (RelativeLayout) rootView.findViewById(R.id.fragment_main_layout);
    
       //And now you can add the buttons you need, because it's a fragment, use getActivity() as context
       Button bt = new Button(getActivity());
       //You can add LayoutParams to put the button where you want it and the just add it
       rl.addView(bt);
    
    
        return rootView;
    }
    

    就是这样,你的布局上有一个新按钮

    【讨论】:

    • 他不能对新按钮使用getBaseContext()吗?顺便说一句,很好的答案。
    • 不是来自Fragment。该方法仅针对Activity 定义
    【解决方案2】:

    我尝试在膨胀之前将按钮添加到布局中,但我不知道如何获取布局:(类型 id 错误的预期资源)

    您的代码应该将其转换为相对布局并查找资源 ID 而不是布局文件。

    RelativeLayout rl = (RelativeLayout) getView().findViewById(R.id.fragment_main_layout);
    

    希望对你有帮助

    【讨论】:

      【解决方案3】:

      您可以使用视图的上下文来创建按钮:

      public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
      {
           View view = inflater.Inflate(Resource.Layout.fragment_question_list, container, false);
      
           Button btn = new Button(view.Context);
      
           return view
      }
      

      【讨论】:

        猜你喜欢
        • 2012-06-19
        • 2016-06-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多